Elasticsearch Java API do not return fields of hits

6.2k views Asked by At

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",
    ...
  }
}
4

There are 4 answers

0
John On BEST ANSWER

the fields are not responding as fields....

with hit.getSource() i got my information

1
SamLeBarbare On

QueryBuilders.matchQuery()

seems to work with fields only

"_type" is a build-in properties of the index...

Try something like that :

    client.prepareSearch("bookings")
      .setTypes("booking")
      .setQuery(query)
      .execute()
      .actionGet();

Your query must be based on your document fields

2
Slomo On

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).

0
kiml42 On

The fields section of a hit includes the fields you explicitly ask for, by default that is none. You can use addField() or addFields() to add one or more fields to the request. This should populate the fields in the response for you.

The source in each hit contains the entire original object, so may well have data you do not need. Returning the source in this manner is often turned off to prevent sending this excess data around.