Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch Java API - building queries

I have looked through the docs for the Search API but find them not descriptive enough (even though they are very well written). I am trying to build a query but understand little about all the different options available and cannot find information on the matter, when building a query and I am unable to translate queries I can run in Sense to queries I can run using the Java API.

In Sense I have the following:

GET index/_search
{
  "query": {
    "match" : {
      "name" : "some string"
    }
  }
}

And in my Java code I have:

node = nodeBuilder().client(true).clusterName(CLUSTER_NAME).node();
client = node.client();
QueryBuilder qb = QueryBuilders.termQuery("name", "some string");
SearchResponse response = client.prepareSearch("index") //
    .setQuery(qb) // Query
    .execute().actionGet();

But they produce different search results. What is the difference as I cannot see it? Also is there a good source of information that might be of use?

like image 497
Neilos Avatar asked Jun 15 '14 01:06

Neilos


1 Answers

If you want the two queries to return the same results you need to use the same type of query. In your Sense query you are performing a match query:

"query": {
    "match" : {
      "name" : "some string"
    }
  }

but in your Java code you are performing a termQuery:

QueryBuilder qb = QueryBuilders.termQuery("name", "some string");

So to answer your question use a match query instead in your Java code:

QueryBuilder qb = QueryBuilders.matchQuery("name", "some string");

Regarding your second question, it's a bit broad. I'd certainly try going thru the documentation and searching here on StackOverflow. Regarding the Java API I'd look here for the overview and here for the info on the query dsl thru Java.

I think a good general understanding of how Elasticsearch works and some comfort with the query mechanism thru the REST API would be very helpful in getting to understand the Java API. Good places to start:

http://joelabrahamsson.com/elasticsearch-101/

http://exploringelasticsearch.com/

http://java.dzone.com/articles/elasticsearch-getting-started

like image 54
John Petrone Avatar answered Nov 01 '22 00:11

John Petrone