0

I would like to use the java client API in order to return a computed field in the response of documents.

Specifically, I want a user to pass in a geopoint and use that geopoint in order to compute the distance between that geopoint (passed in the query) and the documents' geopoints (stored in the ES index).

I understand it is easily feasible using a script field as follows:

curl -XGET 'http://127.0.0.1:9200/geonames/_search?pretty=1'  -d '
{
   "script_fields" : {
      "distance" : {
         "params" : {
            "lat" : 2.27,
            "lon" : 50.3
         },
         "script" : "doc[\u0027location\u0027].distanceInKm(lat,lon)"
      }
   }
}

The above is quoted from the following SO post: https://stackoverflow.com/a/9309674/536299

Now how do you go about doing this with the java API or Spring Data ES?

Community
  • 1
  • 1
balteo
  • 23,602
  • 63
  • 219
  • 412

1 Answers1

1

You can use the below to convert it to java api

    import org.elasticsearch.action.search.SearchRequestBuilder;

    String script =  "doc[\u0027location\u0027].distanceInKm(lat,lon)";
    Map<String, Object> params = ...

    SearchRequestBuilder esRequestBuilder = new SearchRequestBuilder(<ES_CLIENT>);
    esRequestBuilder.addScriptField("distance", script, params);
Rahul
  • 15,979
  • 4
  • 42
  • 63
  • Thanks a lot @rahulroc, Hummm. But then, is the script field used for all document types? How can I relate a type to the above script field? – balteo Mar 31 '16 at 06:16
  • By Type.. you mean the elasticsearch type in an index ? https://www.elastic.co/blog/index-vs-type – Rahul Mar 31 '16 at 06:20
  • 1
    Yes and I also mean the java class annotated with spring data es's @org.springframework.data.elasticsearch.annotations.Document annotation. – balteo Mar 31 '16 at 06:26
  • You can also specify the type in your entity @Document(indexName="myIndex", type="myType"). Then you can search within a type as curl -XGET 'http://127.0.0.1:9200///_search – Rahul Mar 31 '16 at 06:30
  • I see. As regards the java api, how is the field added to the @Document? – balteo Mar 31 '16 at 06:33
  • what field ? I didnt get this – Rahul Mar 31 '16 at 06:57
  • I meant the newly created field, the dynamic/script field. – balteo Mar 31 '16 at 07:02
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/107818/discussion-between-rahulroc-and-balteo). – Rahul Mar 31 '16 at 07:32