0

I'm integrating Hibernate Search in my project and at the moment it works fine.

Now I want to refine my search in this way: basically I'd like to pass, as a user, a query like term1 AND term2 OR term3 and so on. The number of terms could be different of course.

So my idea is to build a proper search with logical operators to help the users to find what they want to.

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
user1341300
  • 375
  • 1
  • 5
  • 19
  • (term1 AND term2) OR term3 ...a mix and match? How would one keeps track of what to be ANDed and what to be ORed? – Anant Laxmikant Bobde Jul 17 '15 at 11:16
  • Why not just us the QueryParser (see [Query documentation](https://docs.jboss.org/hibernate/search/3.2/reference/en-US/html/search-query.html), Example 5.2)? – femtoRgon Jul 17 '15 at 18:08

2 Answers2

0

You have to separate your conditions which are using AND and OR by using (). e.g. (term1 AND term2) OR term3

If you are again wanted to use some term the it should be like ((term1 AND term2) OR term3) AND term4 like this.....

Vickal
  • 161
  • 1
  • 8
0

You can use this stackoverflow answer if you have one entity.

You can use a boolean query like :

Query luceneQuery = b.bool()
    .must(b.keyword().onField("fieldName").matching("term1").createQuery())
    .must(b.keyword().onField("fieldName").matching("term2").createQuery())
    .should(b.keyword().onField("fieldName").matching("term3").createQuery())
    .except(b.keyword().onField("fieldName").matching("term4").createQuery())
    .createQuery();

must : the query must much this term (like AND).

should : the query should this query (like OR).

except : to exclude the document that contains this term (like NOT).

Community
  • 1
  • 1
Bilal BBB
  • 1,154
  • 13
  • 20
  • Thanks for your answer. The thing is, what about if I don't know at prior what it should be MUST and what SHOULD? What I mean is that only the user can type in the search bar some symbols like + or - or whatever to say this is MUST or this SHOULD. Probably the best solution is to provide a kind of query generator in the search bar in order to help the user to create the query properly and then pass the query to Lucene. – user1341300 Jul 20 '15 at 09:50
  • I was wondering if I can let the user write (maybe with an "helper") a query like: "(project: projectName AND user: userName) OR project: projectName2" – user1341300 Jul 20 '15 at 10:46
  • Try to construct a logic that splits the user entered string into terms (if the entered value contains 'and, or, not'), term1 contains words for 'and', term2 contains words for 'or, term3 contains words for 'not' and use these terms in hibernate search. You can use the 'split' function (value.split("and")) with some logic. – Bilal BBB Jul 20 '15 at 11:42