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.

1 Answer 1

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\""
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
See my edit for how to use the Lucene syntax with the Java API.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.