2
votes

While searching the record from elasticsearch using JAVA API, I would like to get nested objects. I have used addFields method to get particular fields, but unable to retrieve the nested object values.

Using Elastic search version 1.1.1

My Codes:

I have a document with fields countryId, countryName and states. States is a nested document list and it will have list of states.

   SearchRequestBuilder builder = client.prepareSearch("tests").setTypes("country")
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH).addFields("countryName", "states");


    MatchQueryBuilder mqb;

    mqb = QueryBuilders.matchPhrasePrefixQuery("name", "ind");
    builder.setQuery(mqb);

    SearchResponse response = builder.execute().actionGet();
    SearchHit[] documents = response.getHits().getHits();

    System.out.println(documents.length);

I want to get states(nested object) and countryName values.

 {"states" : ["stateId" : "1000", "name" : "Kerala"], ["stateId" : "1001", "name" : "Tamil Nadu"]} 
 {"countryName" : "India"}

Issue: - Result document size is coming as zero. Unable to search any data. If I remove nested object list(states) from the given fields, able to search the documents and get the field values.

1
Do you get 0 documents back or some documents but no fields?javanna

1 Answers

0
votes

You need to use the following in your query: Use the setFetchSource(String[] include_fields, String[] exclude_fields);

Nested fields are not leaf fields, they need to be retrieved direct from source. Code:

SearchRequestBuilder builder = client.prepareSearch("tests").setTypes("country")
        .setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setFetchSource(new String[]{"states","countryName"},new String[]{});

You can iterate over them in the result.

HTH, RR.