0

I am trying to do a fulltext search, the only problem i am facing is the fact, that excact matches are not on top of the list. If i search for "cat" then i get "blablacatcc", "asdcatsada" and then "cat". Is there a way to have it sorted like that? With exact matches on top?

my code:

final String[] fields = Stream.of(
            Product_.casNumber.getName(),
            Product_.casIndexName.getName(),
            Product_.chemicalName.getName(),
            path(Product_.alternativeNames, ProductName_.alternativeName)
    ).toArray(String[]::new);
    final QueryBuilder builder = manager.getSearchFactory().buildQueryBuilder().forEntity(Product.class).get();
    final Sort sort = builder.sort().byScore().createSort();
    final Query query = builder.keyword().wildcard().onFields(fields).matching("*" + pattern.toLowerCase() + "*").createQuery();
    return manager.createFullTextQuery(query, Product.class).setSort(sort).getResultList();
gygabyte
  • 176
  • 2
  • 12
  • How does it sort the results without your custom sorter? – Naya Feb 04 '19 at 17:22
  • It seems random, prolly it does not sort at all – gygabyte Feb 04 '19 at 17:25
  • Could you please provide imports? – Naya Feb 04 '19 at 17:35
  • `import org.apache.lucene.search.Query; import org.apache.lucene.search.Sort; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.query.dsl.QueryBuilder;` – gygabyte Feb 05 '19 at 12:45
  • Thanks, which dependencies do you use? I can't see `sort()` method on QueryBuilder class using org.hibernate:hibernate-search-engine:4.3.0 – Naya Feb 05 '19 at 12:54
  • org.hibernate:hibernate-search-orm:5.10.0.Final – gygabyte Feb 05 '19 at 13:32
  • I found out only one solution for that: https://stackoverflow.com/questions/18725941/mysql-order-by-best-match Here in answers is an idea to create order by-case. My best proposal to sort the collection in this way after you got the result. Of course if you don't need limits for it. – Naya Feb 05 '19 at 13:45
  • Going with raw sql is not a possibility – gygabyte Feb 05 '19 at 13:54
  • Sure, that’s why I talk about sorting the result collection with Java. Not using sql – Naya Feb 05 '19 at 14:00

0 Answers0