jlgarhdez
jlgarhdez

Reputation: 33

Obtaining string query (JSON) from SearchQuery object

For debugging purposes, I need to know what query spring-data-elasticsearch is sending to the ElasticSearch cluster. I have tried to call the toString method on the SearchQuery object, and doesn't return what I need.

What I am doing in Java (using spring-data-elasticsearch) is:

private FilterBuilder getFilterBuilder(String id) {
    return orFilter(
        termFilter("yaddayaddayadda.id", id),
        termFilter("blahblahblah.id", id)
    );
}


SearchQuery sq = NativeSearchQueryBuilder()
    .withQuery(new MatchAllQuery())
    .withFilter(fb)
    .build();

And I expect to return something like this plain query executed in ES cluster REST API is returning:

{
    "query": {
        "filtered": {
            "filter": {
                "or": [
                    {
                        "term": {
                            "yaddayaddayadda.id": "9"
                        }
                    },
                    {
                        "term": {
                            "blahblahblah.id": "9"
                        }
                    }
                ]
            }
        }
    }
}

Thanks in advance!

Upvotes: 3

Views: 6454

Answers (3)

Hamid Mohayeji
Hamid Mohayeji

Reputation: 4285

When using SearchRequest or SearchSourceBuilder, calling .toString() method on their instance will get you actual JSON query:

SearchRequest searchRequest = new SearchRequest("index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

// building the query
// ...

searchSourceBuilder.query(query);
searchRequest.source(searchSourceBuilder);

System.out.println(searchSourceBuilder.toString()); // prints json query
System.out.println(searchRequest.toString()); // prints json query + other information

Upvotes: 2

Mohsin Husen
Mohsin Husen

Reputation: 1008

SearchQuery Interface has a method getQuery() and getFilter() to get the information you need.

        System.out.println(searchQuery.getQuery());
        System.out.println(searchQuery.getFilter());

Hope this helps.

Upvotes: 1

Val
Val

Reputation: 217314

One way to achieve this is to log the queries on the ES/server-side into the slowlog file. Open your elasticsearch.yml config file and towards the bottom uncomment/edit the two lines below:

...
index.search.slowlog.threshold.query.info: 1ms
...
index.search.slowlog.threshold.fetch.info: 1ms
...

The advantage of this solution is that whatever client technology you're using to query your ES server (Spring Data, Ruby, Browser, Javascript, etc), you'll be able to dump and debug your queries in a single location.

Upvotes: 5

Related Questions