简体   繁体   中英

How to search a full phrase along with single terms using Hibernate Lucene?

Earlier we searching like "Father David Azrael". It returns all results names with term Father or David or Azrael.

Following was code in picture:

String[] FIELDS =  { "id", "person.firstName", "person.middleName", "person.lastName" };
for (String field : FIELDS) {
           for (String match : pattern) {     
                   bool.should(qb.keyword().wildcard().onField(field).matching(match).createQuery());
           }
        }
        query = bool.createQuery();

Along with above scenario, now there is additional requirement that if end user want to search "Father David Azrael"; he should get one result only.

Means if we search "Father David Azrael"; then only results having this name should appears but if user search "Father Azrael" then it should work as working now.

So what changes need to be done with above code to implement the same?

You can use a phrase query, as shown in section 5.1.2.4 of the documentation:

bool.should(qb
    .phrase()
    .onField(field)
    .sentence("Father David Azrael")
    .createQuery());

I don't know what you mean about "Father David Azrael" being treated differently than "Father Azrael", so I won't comment on that part, but that's how you would create a phrase query. You could combine the phrase with the existing wildcard queries by adding both to your boolean query to get both sets of results, with the phrase matches generally receiving the highest scores. Or you could just run the phrase query first, and fall back on the wildcard queries when that gets no results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM