0

I am new to Elastic Search.I want to include multiple field in my search query something like:

      Title=my title and city=mycity or country = mycountry

How can I execute this kind of query using java client? I tried this

SearchResponse response = client.prepareSearch("titan")
    .setTypes("vertex")
    .setSearchType(SearchType.QUERY_AND_FETCH)
    .setQuery(QueryBuilders.fieldQuery("title", "mytitle"))
    .setQuery(QueryBuilders.fieldQuery("city", "mycity"))
    .setFrom(0).setSize(60).setExplain(true)
    .execute()
    .actionGet();

but didn't work

1 Answer 1

1

You have to do booleanQuery there, I believe.

Something like:

SearchResponse response = client.prepareSearch("titan")
    .setTypes("vertex")
    .setSearchType(SearchType.QUERY_AND_FETCH)
    .setQuery(QueryBuilders.boolQuery()
    .must(QueryBuilders.fieldQuery("title", "mytitle"))
    .should(QueryBuilders.fieldQuery("city", "mycity"))
    .should(QueryBuilders.fieldQuery("country", "mycountry")))
    .setFrom(0).setSize(60).setExplain(true)
    .execute()
    .actionGet();

The rules for boolean queries, in a nutshell, are that all must clauses are expected to be true, and at least one from the should clauses are expected to be true (the amount of should clauses which has to be true can be changed, one is the default).

Sign up to request clarification or add additional context in comments.

4 Comments

.must(QueryBuilders.fieldQuery("country", "IN")) it work but if i use .must(QueryBuilders.fieldQuery("country", "in")) it doesnt. why?
Perhaps you country field is not analyzed?
then why it is fetching for IN
I guess because when it's indexing the data, the country field is provided as "IN", and perhaps in the mapping it is specified as "not analyzed". that means it's not tokenized and taken as-is (case-sensitive, among other things). But it's just a guess, for the exact answer you need to know how the data are indexed.

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.