Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing nested elasticsearch fields in java

So far I followed this guide to get native java scripts working with elasticsearch. Accessing normal non-nested fields works fine using doc().field("fieldname").

Does the same work for nested fields? How can I loop over them and access nested fields?

EDIT: After reading imotov's answer below I ended up including the nested field in the root document using include_in_root or include_in_parent (See docs).

GeoPoint[] locations = ((GeoPointDocFieldData)doc().field("places.location")).getValues();

for (GeoPoint location : locations) {
    // Do Stuff
    double lat = location.lat();
    double lon = location.lon();
}
like image 993
sqwk Avatar asked Jun 06 '26 03:06

sqwk


1 Answers

This is tough one. The nested objects are indexed internally as separate documents, so the top level custom_filters_score is operating on the root object and doesn't have access to nested objects. But there is a few things you can do.

The best option in my opinion is to move custom_filters_score into the nested filter where your script will run on the nested objects. See Elastic search - tagging strength (nested/child document boosting) as an example.

The second option is to set include_in_root setting to true on the nested object mapping. This way all your nested object fields will be indexed in the root objects as well and you will be able to access them using dot notation: places.location as if were not nested. The problem with this option is that you will have to index fields twice and you will not know which nested object matched your nested query.

The third option is to retrieve nested object fields from source. This is going to be really slow and not really applicable if your searches produce a lot of results.

like image 188
imotov Avatar answered Jun 10 '26 02:06

imotov