Hi I am new ElasticSearch, I am using spring data. I have 2 API which saves data in article and discourse model using elastic search, now when a client app makes a API call for both article and discourse search it gives all article first and then discourse data. but i want to randomize the response how can i do that?
my article model class as follows
#AllArgsConstructor
#Data
#Document(indexName="articles", createIndex=true)
public class Article implements ITResult {
private String id;
private String hostContentId;
private String title;
private List<String> categories;
private String searchResultId;
#Override
public String getSummary() {
return excerpt;
}
#Override
public ContentType getContentType() {
return ContentType.ARTICLE;
}
#Override
public String getHostContentId() {
return hostContentId;
}
#Override
public String getUrl() {
return link;
}
#Override
public String getSearchResultId() {
return searchResultId;
}
public void setSearchResultId(String searchResultId) {
this.searchResultId = searchResultId;
}
}
I have done the following
SearchQuery query = new NativeSearchQueryBuilder().withIndices("articles","course")
.withPageable(new PageRequest(offset,limit))
.withFilter(multiMatchQuery(string, new String[] { "title", "excerpt", "author_name", "link"}))
.build();
Related
I have created a RESTful webservice using Spring boot to add a record to H2 database but when I send data from postman to my handler method I get null values on the server side and on the response sent to the client side as well, could anybody help me?
Eclipse Snapshot
Postman Snapshot
My Controller Code:
#RestController
public class AlienController {
#Autowired
AlienRepo repo;
#RequestMapping("/")
public String home() {
return"home.jsp";
}
#PostMapping(path="/alien")
public Alien addAlien(Alien alien) {
System.out.println(alien);
repo.save(alien);
return alien;
}
My DAO Class:
#Entity
public class Alien {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int aid;
private String aname;
private String lang;
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid=aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname=aname;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang=lang;
}
#Override
public String toString() {
return "Alien Info: Aid=" + aid + ", Aname=" + aname + ", Lang=" +lang;
}
}
My AlienRepository code:
public interface AlienRepo extends JpaRepository<Alien, Integer>{
}
You should use the annotation #RequestBody
public Alien addAlien(#RequestBody Alien alien)
You should inform Spring that you are waiting for a HttpRequest that contains a Body , Spring will automatically deserialize the inbound HttpRequest body onto Java object
I'm using retrofit with gson in android, i'm following a tutorial so the guy on the tutorial make it work but i can't
it looks like my json data is lost when i call the retrofit method here are my call in android
ANDROID ACTIVITY.JAVA
public void addProspecto(Prospecto p){
prospectoService= Apis.getProspectoService();
Call<Prospecto>call=prospectoService.addProspecto(p);
call.enqueue(new Callback<Prospecto>() {
#Override
public void onResponse(Call<Prospecto> call, Response<Prospecto> response) {
if(response.isSuccessful()){
Toast.makeText(ProspectoActivity.this,"Se agrego con éxito",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Prospecto> call, Throwable t) {
Log.e("Error:",t.getMessage());
}
});
ANDROIDINTERFACE.JAVA
#POST("agregar")
Call<Prospecto>addProspecto(#Body Prospecto prospecto);
backend in springtools java
ProspectoController.java
#RestController
#RequestMapping("/prospectos")
public class ProspectoController {
#Autowired
private ProspectoService service;
#GetMapping("/listar")
public List<Map<String, Object>> listar(){
return service.listar();
}
#PostMapping("/agregar")
#ResponseBody
public String save(#RequestBody Prospecto p) {
System.out.println("#############################");
System.out.println(p.getNombre());
int id=service.add(p);
if(id==0) {
return "No se pudo Regsitrar!";
}
return "Se registró con éxito!";
}
Prospecto model.java
#Data
public class Prospecto {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int ID;
private String nombre;
private String apPaterno;
private String apMaterno;
private String calle;
private String numero;
private String colonia;
private String cP;
private String telefono;
private String rFC;
private File documentos;
private String statusProspecto;
}
And for the last the repository or the file where i use the sql querys :
ProspectoDAO
#Repository
public class ProspectoDAO implements ProspectoInterface {
#Autowired
JdbcTemplate template;
#Override
public List<Map<String, Object>> listar() {
// TODO Auto-generated method stub
List<Map<String, Object>>lista=template.queryForList("Select * from prospectos");
return lista;
}
#Override
public List<Map<String, Object>> listar(int id) {
// TODO Auto-generated method stub
return null;
}
#Override
public int add(Prospecto p) {
String sql = "insert into prospectos(Nombre, apPaterno, apMaterno, Calle, Numero, Colonia, CP, Telefono, RFC, Documentos, statusProspecto)values(?,?,?,?,?,?,?,?,?,?,?)";
return template.update(sql,
p.getNombre(),
p.getApPaterno(),
p.getApMaterno(),
p.getCalle(),
p.getNumero(),
p.getColonia(),
p.getCP(),
p.getTelefono(),
p.getRFC(),
p.getDocumentos(),
p.getStatusProspecto()
);
}
Please help, i'm sending the object ''Prospecto'' with ''nombre'' and all the data needed for it and in my backend it stills says that i don't have the data
In my database the column ''nombre'' were ''Nombre'' with capitals so thats was all i guess. For anyone who have the same problem check the getters and setters and put it the same as they are in the columns database.
I want to store a List of class : RestApiResponse into MySql. But getting below error:
org.hibernate.HibernateException: Could not determine a type for class: com.try.sreapi.beans.RestApiResponse
Below are my classes:
Entity class : SREAPITestingHistory.java
#NamedQueries(#NamedQuery(name="getSREAPITestHistory.findAll", query="SELECT a FROM SREAPITestingHistory a"))
#SqlResultSetMapping(name="sreapitestinghistoryres",
entities=#EntityResult(entityClass=SREAPITestingHistory.class))
#Entity
#Table(name="sreapi_testing_history_details")
#Transactional
public class SREAPITestingHistory implements Serializable{
private static final long serialVersionUID = -7221709766109001257L;
#Id
#Column(name="request_time")
private String request_time;
#Column(name="req_id")
private String req_id;
#Column(name="app_name")
private String app_name;
#Column(name="request_name")
private String request_name;
#Lob
#Column(name="response_body")
private List<RestApiResponse> response;
public String getRequest_time() {
return request_time;
}
public void setRequest_time(String request_time) {
this.request_time = request_time;
}
public String getReq_id() {
return req_id;
}
public void setReq_id(String req_id) {
this.req_id = req_id;
}
public String getApp_name() {
return app_name;
}
public void setApp_name(String app_name) {
this.app_name = app_name;
}
public String getRequest_name() {
return request_name;
}
public void setRequest_name(String request_name) {
this.request_name = request_name;
}
public List<RestApiResponse> getResponse() {
return response;
}
public void setResponse(List<RestApiResponse> response) {
this.response = response;
}
}
Repository Class: SREAPITestingRepository.java
#Repository
public interface SREAPITestingRepository extends CrudRepository< SREAPITestingHistory, String> {
#Modifying
#Transactional
#Query(value="INSERT into sreapi_testing_history_details (request_time,req_id,app_name,request_name,response_body)"+ "VALUES (:request_time,:req_id,:app_name,:request_name,:response_body)", nativeQuery = true)
public void setApiTestHistoryDetails(#Param("request_time") String request_time,#Param("req_id") String req_id,#Param("app_name") String app_name,#Param("request_name") String request_name,#Param("response_body") List<RestApiResponse> response_body);
}
When I am trying to add values for response_body which is actually a List of RestApiResponse class and I am getting Could not determine a type for class: com.try.sreapi.beans.RestApiResponse exception
From Official doc
A Lob may be either a binary or character type.
The Lob type is inferred from the type of the persistent field or
property, and except for string and character-based types defaults to
Blob.
Example 1:
#Lob #Basic(fetch=LAZY) #Column(name="REPORT")
String report;
Example 2:
#Lob #Basic(fetch=LAZY) #Column(name="EMP_PIC",
columnDefinition="BLOB NOT NULL") protected byte[] pic;
So you can convert your list of data into json string or bytes to store.
I have installed solr-6.5.1 in my Spring MVC Java Web Application refering the following documentations:
http://www.baeldung.com/apache-solrj
https://github.com/eugenp/tutorials/tree/master/apache-solrj/src/main/java/com/baeldung/solrjava
I have a POJO declared as shown below:
public class WebContentSearchHB
{
private int webContentDefinitionId;
private String pageTitle;
private String pageKwd;
private String pageDesc;
private int siteId;
private int applicationId;
private Date pageCreatedTime;
private Date pageUpdatedDate ;
private String webContentData;
private String webContentType;
private String category;
public int getWebContentDefinitionId()
{
return webContentDefinitionId;
}
#Field("webContentDefinitionId")
public void setWebContentDefinitionId(int webContentDefinitionId)
{
this.webContentDefinitionId = webContentDefinitionId;
}
public String getPageTitle()
{
return pageTitle;
}
#Field("pageTitle")
public void setPageTitle(String pageTitle)
{
this.pageTitle = pageTitle;
}
public String getPageKwd()
{
return pageKwd;
}
#Field("pageKwd")
public void setPageKwd(String pageKwd)
{
this.pageKwd = pageKwd;
}
public String getPageDesc()
{
return pageDesc;
}
#Field("pageDesc")
public void setPageDesc(String pageDesc)
{
this.pageDesc = pageDesc;
}
public int getSiteId()
{
return siteId;
}
#Field("siteId")
public void setSiteId(int siteId)
{
this.siteId = siteId;
}
public int getApplicationId()
{
return applicationId;
}
#Field("applicationId")
public void setApplicationId(int applicationId)
{
this.applicationId = applicationId;
}
public Date getPageCreatedTime()
{
return pageCreatedTime;
}
#Field("pageCreatedTime")
public void setPageCreatedTime(Date pageCreatedTime)
{
this.pageCreatedTime = pageCreatedTime;
}
public Date getPageUpdatedDate()
{
return pageUpdatedDate;
}
#Field("pageUpdatedDate")
public void setPageUpdatedDate(Date pageUpdatedDate)
{
this.pageUpdatedDate = pageUpdatedDate;
}
public String getWebContentData()
{
return webContentData;
}
#Field("webContentData")
public void setWebContentData(String webContentData)
{
this.webContentData = webContentData;
}
public String getWebContentType()
{
return webContentType;
}
#Field("webContentType")
public void setWebContentType(String webContentType)
{
this.webContentType = webContentType;
}
public String getCategory() {
return category;
}
#Field("category")
public void setCategory(String category) {
this.category = category;
}
}
I haven't created any schema.xml file or edited the existing schema.xml file. I am manually setting the values for each field in the POJO and adding it to the Solr index using my application as follows:
solrClient = new HttpSolrClient.Builder(solrUrl).build();
solrClient.setParser(new XMLResponseParser());
WebContentSearchHB searcHB = new WebContentSearchHB();
//codes to set data
solrClient.addBean(searcHB);
solrClient.commit();
I have also added the following maven dependency to my pom.xml file
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>6.5.1</version>
</dependency>
One of my fields in the WebContentSearchHB class, named category will contain a comma separated string of ids of various categories for that content.
A sample data would look like the one shown below:
[
{"pageTitle":["Test page"],
"pageKwd":["Test page"],
"pageDesc":["Test page"],
"applicationId":[1],
"siteId":[5],
"category":["2,6,7,8"],
"pageCreatedTime":["2017-02-17T05:58:19.648Z"],
"pageUpdatedDate":["2017-06-12T03:46:45.489Z"],
"webContentDefinitionId":[4947],
"webContentType":["simplewebcontent.html"],
"id":"717821d9-989e-4c4f-b66a-8b5185ed88ca",
"webContentData":"test"],
"_version_":1570012287149801472}
]
here there are multiple categories added as comma seperated values. Now when I try search for the data in the catagory field as follows:
http://localhost::8983/solr/swcm_qa/select?indent=on&q=category:7*&wt=json
no data is returned. But if I search as follows,
http://localhost::8983/solr/swcm_qa/select?indent=on&q=category:2*&wt=json
All rows where 2appears as the first value in the comma separated string is returned. How can I search for a string from among the comma separated values in the category field? Also, how can I specify if the field is storing multiple values as comma separated string in the #Field annotation?
In category field "2,6,7,8" is indexed as single string
category:["2,6,7,8"]
It should be like
category:["2","6","7","8"]
Either you should apply filter to that category field before indexing so that it stores individual numeric value into the field with ,as delimiter
OR
modify query like q=category:*7*
i have small web application in spring mvc and hibernate.
in this web service via push notification to database into data is automatically push into android device.
how to do push notification?
restful controller
#Controller
#RequestMapping("/json")
public class JsonData
{
#Autowired
private AdminService adminService;
#GET
#RequestMapping(value="/jsonEnglishWord")
#Produces(MediaType.APPLICATION_JSON)
public #ResponseBody List<English_Word> getAllWord() {
return new ArrayList<English_Word>(adminService.getAllWord());
}
#GET
#RequestMapping(value="/jsonGujaratiWord")
#Produces(MediaType.APPLICATION_JSON)
public #ResponseBody List<Gujarati_Word> getallGujarati_Words(){
return new ArrayList<Gujarati_Word>(adminService.getAllGujaratiword());
}
database model
#Entity
#Table(name="English_Word")
public class English_Word {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int word_id;
private String word_name;
#Lob
private String word_explain;
#Temporal(TemporalType.DATE)
private Date word_date;
public int getWord_id() {
return word_id;
}
public void setWord_id(int word_id) {
this.word_id = word_id;
}
public String getWord_name() {
return word_name;
}
public void setWord_name(String word_name) {
this.word_name = word_name;
}
public String getWord_explain() {
return word_explain;
}
public void setWord_explain(String word_explain) {
this.word_explain = word_explain;
}
public Date getWord_date() {
return word_date;
}
public void setWord_date(Date word_date) {
this.word_date = word_date;
}
}
Please refer following link. It helps me. check for java code. first create app on google
http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/