Search code examples
javaelasticsearch

Converting elastic search CURL request into java


I have the below functioning curl request

curl -X POST "localhost:9200/search_request/_search" -H 'Content-Type: application/json' -d '{
  "query": {
    "bool": {
      "must": {
        "exists": {
          "field": "logRequestId"
        }
      }
    }
  }
}'

Now, I want to get the java code to do this.

I know there are various methods e.g. SearchSourceBuilder in Rest High Level client to do so. But my elastic client is Low level. Following is the code where I establist connection to the ES client

RestClient restClient = RestClient.builder(new HttpHost(elasticsearchHostname, elasticsearchPort)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        this.esClient = new ElasticsearchClient(transport);

Is there any way to achieve the objective possibly in a production ready code?


Solution

  • It should be something like this:

    SearchResponse<Void> response = esClient.search(sr -> sr
        .index("search_request")
        .query(q -> q.exists(eq -> eq.field("logRequestId")))
    , Void.class);
    

    I added it as a test in my demo project. I also recommend reading this blog post.