0

I've recently started using ElasticSearch. I've managed to integrate them successfully, but I find the search API rather complex and confusing. The Java API is not too helpful either. How is it possible to search the following JSON for the fieldname title with Lucene syntax AND and OR using java api?

{
    "queryId": 2,
    "queryName": "beta",
        "query": {
            "lang": "en",
            "location": "pa",
            "title": "americanlegion OR concernedvets AND conversion"
      }
  }

I've tried boolean query but they don't feed my purpose.

Saeed Zhiany
  • 2,051
  • 9
  • 30
  • 41
Jay
  • 471
  • 1
  • 4
  • 11

1 Answers1

3

It would be good if you could show what you tried with the BoolQuery and explain why it didn't work. Here is an example of your query using the Java API's BoolQuery.

BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.should(QueryBuilders.termsQuery("lang", "en"));
boolQuery.should(QueryBuilders.termsQuery("location", "en"));

BoolQueryBuilder titleBoolQuery = QueryBuilders.boolQuery();
titleBoolQuery.should(QueryBuilders.termsQuery("title", new String[]{"americanlegion", "conversion"}));
titleBoolQuery.must(QueryBuilders.termQuery("title", "conversion"));

boolQuery.should(titleBoolQuery);

Resulting JSON:

{
    "bool" : {
        "should" : [ {
            "terms" : {
                "lang" : [ "en" ]
            }
        },{
            "terms" : {
                "location" : [ "pa" ]
            }
        },{
            "bool" : {
                "must" : {
                    "term" : {
                         "title" : "conversion"
                    }
                },
                "should" : {
                    "terms" : {
                        "title" : [ "americanlegion", "conversion" ]
                     }
                }
            }
       } ]
   }
}

EDIT

If you want to use the Lucene syntax use the QueryStringQueryBuilder

QueryStringQueryBuilder query = QueryBuilders.queryString("user.name:\"John\" OR user.name:\"Matt\"");

this will produce the JSON

{
    "query_string" : {
        "query" : "user.name:\"John\" OR user.name:\"Matt\""
    }
}
Dan Tuffery
  • 5,874
  • 29
  • 28
  • The user enters a Lucene query. for example: John OR Matt and the JSON looks like: "LQuery":{"query":"user.name:\\\"John\\\" OR user.name:\\\"Matt\\\""} How can this be queried using ES java api? – Jay Aug 25 '14 at 22:48
  • See my edit for how to use the Lucene syntax with the Java API. – Dan Tuffery Aug 26 '14 at 05:15