Reputation: 33
Personal I have a problem in a query, want to put the AND clause in a term, however I am not getting and tried searching with no success.
Follow the example and return the query (I'm using to test Luke conditions upon my indece and the result are different)
builder.bool()
.should(builder
.bool()
.should(builder.keyword()
.onFields("campo01", "campo02", "campo03")
.matching(query).createQuery())
.should(builder.keyword().wildcard().onField("campo01")
.matching("*" + query + "*").createQuery())
.should(builder.keyword().wildcard().onField("campo02")
.matching("*" + query + "*").createQuery())
.should(builder.keyword().wildcard().onField("campo03")
.matching("*" + query + "*").createQuery()).createQuery())
.must(builder.keyword().onField("campo04").matching(0).createQuery())
.createQuery();
This code generates the following query lucene:
(((campo01:teste campo02:test campo03:teste) campo01:*teste* campo02*teste* campo03:*teste*) +campo04:0)
However this query is returning a result larger than expected. Conducting tests with Luke realized that Must was not ideal, needing to be the AND in place.
(((campo01:teste campo02:test campo03:teste) campo01:*teste* campo02*teste* campo03:*teste*) AND campo04:0)
Thus the result is correct, however I could not make the build query to create this result.
Can anyone help or have any questions remained. What I really want is to put an AND condition in a particular field.
Upvotes: 3
Views: 2795
Reputation: 33341
You have the right idea with using the 'must' and 'should' clauses. You can construct a query that creates, effectively, a logical AND using them. You're missing one thing. The structure of an AND, such as:
query1 AND query2
Would be:
+query1 +query2
You're example misses the '+', or Must clause, on the first query, so while the second is required, the first isn't, though it influences the results weight.
So, specifically, what you want is
builder.bool()
.must(builder
.bool()
.should(builder.keyword()
.onFields("campo01", "campo02", "campo03")
.matching(query).createQuery())
.should(builder.keyword().wildcard().onField("campo01")
.matching("*" + query + "*").createQuery())
.should(builder.keyword().wildcard().onField("campo02")
.matching("*" + query + "*").createQuery())
.should(builder.keyword().wildcard().onField("campo03")
.matching("*" + query + "*").createQuery()).createQuery())
.must(builder.keyword().onField("campo04").matching(0).createQuery())
.createQuery();
Or...
(+((campo01:teste campo02:test campo03:teste) campo01:*teste* campo02*teste* campo03:*teste*) +campo04:0)
Upvotes: 2