Azazil
Azazil

Reputation: 77

Elasticsearch - type a query in java

the following query gets all documents in index "geoshapes" that have the location {32.0, 34.0}, how can I do the same in java?

GET /geoshapes/_search
{
  "query": {
    "bool": {
      "filter": {
        "geo_shape": {
          "coordinates": {
            "relation": "contains",
            "shape": {
              "coordinates": [
                32.0,
                34.0
              ],
              "type": "point"
            }
          }
        }
      },
      "must": {
        "match_all": {}
      }
    }
  }
}

Upvotes: 1

Views: 666

Answers (1)

cmhteixeira
cmhteixeira

Reputation: 967

You need to import to your project a library that knows how to communicate with the ElasticSearch instance and do those queries programmatically (i.e. through your Java code). In other words, you need the Java client.

Have a look at: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.13/index.html

Once you imported the library into your project, you can:

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.common.geo.ShapeRelation;
import org.elasticsearch.common.geo.builders.CoordinatesBuilder;
import org.elasticsearch.common.geo.builders.MultiPointBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.GeoShapeQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import static org.elasticsearch.index.query.QueryBuilders.geoShapeQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;

BoolQueryBuilder query1 = QueryBuilders.boolQuery();

GeoShapeQueryBuilder qb = geoShapeQuery(
        "location",
        new MultiPointBuilder(
                new CoordinatesBuilder()
                        .coordinate(32.0, 34.0)
                        .build()));

qb.relation(ShapeRelation.CONTAINS);

query1.filter(qb).must(matchAllQuery());

SearchRequest searchRequest = new SearchRequest("geoshapes");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(query1);
searchRequest.source(searchSourceBuilder);

Elastic has documentation on the client that will be useful to you.

Upvotes: 2

Related Questions