Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch Java API do not return fields of hits

I have a problem with the java api for elasticsearch.

When I do a search like this:

MatchQueryBuilder query = QueryBuilders.matchQuery("_type", "booking");

SearchResponse searchResponse = client.prepareSearch().setQuery(query).execute().actionGet();

for (SearchHit hit : searchResponse.getHits()){
    Map<String, SearchHitField> fields = hit.getFields();
    System.out.println(fields.size());
}

my response never has fields, can somebody help me ? enter image description here

I'am using:

elasticsearch java api 1.4.0 elasticsearch 1.4.0

and my data looks like

{
  "_index": "bookings",
  "_type": "booking",
  "_id": "50245171",
  "_score": 1,
  "_source": {
    "field1": "value1",
    "field2": "value2",
    "field3": "value3",
    ...
  }
}
like image 798
John Avatar asked Apr 11 '26 23:04

John


2 Answers

Have you tried adding .addFields() to your query?

SearchResponse searchResponse = client.prepareSearch().setQuery(query).addFields("field1", "field2",...).execute().actionGet();

I'm not sure about all details, but I believe elasticsearch tries to send you as few data as possible. Which makes sense, since it should be fast and light.

In any case, are you by any chance indexing Booking objects? Because if you need the whole object again, you could also just fetch the source and transform that back into its original Booking object. For example:

ObjectMapper mapper = new ObjectMapper();
Booking booking = mapper.readValue(hit.getSourceAsString(), Booking.class);

ObjectMapper is from com.fasterxml.jackson.databind.ObjectMapper (should be included with elasticsearch I believe).

like image 114
Slomo Avatar answered Apr 13 '26 12:04

Slomo


the fields are not responding as fields....

with hit.getSource() i got my information

like image 45
John Avatar answered Apr 13 '26 11:04

John



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!