简体   繁体   中英

Unable to retrieve nested objects using ElasticSearch Java API

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM