Mohan Shanmugam
Mohan Shanmugam

Reputation: 690

Elasticsearch java client search nested field not working

I am able to successfully create an index using java api and search the source field. My Problem is not able to get the nested key field using search.

For ex my sample json stucture:

{
    "name":         "John Smith",
    "age":          42,
    "confirmed":    true,
    "join_date":    "2014-06-01",
    "timestamp": "14331222299",
    "home": {
        "lat":      51.5,
        "lon":      0.1
    },
    "accounts": [
        {
            "type": "facebook",
            "id":   "johnsmith"
        },
        {
            "type": "twitter",
            "id":   "johnsmith"
        }
    ]
}

i can able to index this json as source through java client api:-

 IndexResponse response = client.prepareIndex(mohan+"-"+14-10-2014, "mohanelastic")
                    .setSource(jsonoutput.toString())
                    .execute()
                    .actionGet();

My java client search api:

   QueryBuilder en = QueryBuilders.matchQuery("name", "John Smith");

FilterBuilder flb = FilterBuilders.andFilter(
                            FilterBuilders
                        .              .rangeFilter("timestamp").from(starttimeinmilli).to(endtimeinmilli),
                                                            FilterBuilders.queryFilter(QueryBuilders.matchQuery("confirmed", "true"))
                            );
            SearchResponse response = client.prepareSearch(mohan+"-"+14-10-2014)        
            .setTypes("mohanelastic")
            .setSearchType(SearchType.QUERY_AND_FETCH)
            .setPostFilter(flb)
            .setQuery(en)
            .setFrom(0).setSize(60)
            .execute().actionGet();

In this i can able to get the total hits, key field values(name,age,join_date). But not able to get the key value for (home.lat) it shows null value. Nested values for any json shows null.

I am retrieving the source field json keys and it shows respective value:-

System.out.println("event type"+response.getHits().getAt(0).getSource().get("name"));
System.out.println("event type"+response.getHits().getAt(0).getSource().get("timestamp"));

But when i try home.lat it shows null value:

System.out.println("event type"+response.getHits().getAt(0).getSource().get("home.lat"));

Upvotes: 1

Views: 2311

Answers (1)

Dan Tuffery
Dan Tuffery

Reputation: 5924

You can't access home.lat value using dot notation in the Java API. Think of nested objects as maps (home) or a list containing maps (accounts). To get the lat value you would need to do the following:

Map<String, Object> source = response.getHits().getAt(0).getSource();
Map<String, Object> home = source.get('home');
Double latValue = (Double) home.get('lat');

Upvotes: 3

Related Questions