1

I have two fields in an entity class:

  1. establishmentName
  2. contactType

contactType has values like PBX, GSM, TEL and FAX

I want a scoring mechanism as to get the most matching data first then PBX, TEL, GSM and FAX.

Scoring:

  • On establishmentName to get the most matching data first
  • On contactType to get first PBX then TEL and so on

My final query is:

(+establishmentName:kamran~1^2.5 +(contactType:PBX^2.0 contactType:TEL^1.8 contactType:GSM^1.6 contactType:FAX^1.4))

But it not returning the result.

My question is, how to boost a specific field on different values basis ?

We can use the following query for two different fields:

Query query = qb.keyword()
    .onField( field_one).boostedTo(2.0f)
    .andField( field_two)
    .matching( searchTerm)
    .createQuery();

But i need to boost a field on its values as in my case it is contactType.

My dataset:
(establishmentName : Concert Decoration, contactType : GSM), (establishmentName : Elissa Concert, contactType : TEL), (establishmentName : Yara Concert, contactType : FAX), (establishmentName : E Concept, contactType : TEL), (establishmentName : Infinity Concept, contactType : FAX), (establishmentName : SD Concept, contactType : PBX), (establishmentName : Broadcom Technical Concept, contactType : GSM), (establishmentName : Concept Businessmen, contactType : PBX)

By searching the term=concert(fuzzy query on establishmentName), it should return me the list as below: (establishmentName : Elissa Concert, contactType : TEL)

[term=concert, exact matching so it will be on top by keeping the order as PBX, TEL, GSM and FAX]

(establishmentName : Concert Decoration, contactType : GSM)

[term=concert, exact matching and by keeping the order as PBX, TEL, GSM and FAX]

(establishmentName : Yara Concert, contactType : FAX)

[term=concert, exact matching and by keeping the order as PBX, TEL, GSM and FAX]

(establishmentName : Concept Businessmen, contactType : PBX)

[term=concert, partial matching and keeping the order as PBX, TEL, GSM and FAX]

(establishmentName : SD Concept, contactType : PBX)

[term=concert, partial matching and keeping the order as PBX, TEL, GSM and FAX]

(establishmentName : E Concept, contactType : TEL)

[term=concert, partial matching and keeping the order as PBX, TEL, GSM and FAX]

(establishmentName : Broadcom Technical Concept, contactType : GSM)

[term=concert, partial matching and keeping the order as PBX, TEL, GSM and FAX]

(establishmentName : Infinity Concept, contactType : FAX)

[term=concert, partial matching and keeping the order as PBX, TEL, GSM and FAX]

3
  • Your definition of the sort should be refined. What does "most matching data" mean? Do you mean "documents with a score higher than X"? Or "documents that match first, then documents that do not match"? It will probably be easier if you give examples of datasets, and how you expect the sorted results to look like. Do not forget to take into account paging.
    – yrodiere
    Jan 9, 2020 at 12:56
  • @yrodiere i want to make the results ordered by scoring based on 2 criteria: first criteria(fuzzy query on establishmentName), here "most matching data" mean "documents same or most close to the search term in the query: second criteria(contactType has values like PBX, GSM, TEL and FAX), to get order as first PBX then GSM and so on. here i want to set contactType values scores and then combine it with the fuzzy one. Jan 9, 2020 at 13:17
  • @yrodiere i have provided the datasets in the post. Please have a look in the post. Thanks Jan 13, 2020 at 7:01

1 Answer 1

1

From what I understand you basically want a two-phase sort:

  1. Put exact matches before other (fuzzy) matches.
  2. Sort by contact type.

The second sort is trivial, but the first one will require a bit of work. You can actually rely on scoring to implement it.

Essentially the idea would be to run a disjunction of multiple queries, and to assign a constant score to each query.

Instead of doing this:

Query query = qb.keyword()
    .fuzzy().withEditDistanceUpTo(1)
    .boostedTo(2.5f)
    .onField("establishmentName")
    .matching(searchTerm)
    .createQuery();

Do this:

Query query = qb.bool()
    .should(qb.keyword()
        .withConstantScore().boostedTo(100.0f) // Higher score, sort first
        .onField("establishmentName")
        .matching(searchTerm)
        .createQuery())
    .should(qb.keyword()
        .fuzzy().withEditDistanceUpTo(1)
        .withConstantScore().boostedTo(1.0f) // Lower score, sort last
        .onField("establishmentName")
        .matching(searchTerm)
        .createQuery())
    .createQuery();

The matched documents will be the same, but now the query will assign predictable scores: 1.0 for fuzzy-only matches, and 101.0 (1 from the fuzzy query and 100 from the exact query) for exact matches.

This way, you can define the sort as follows:

fullTextQuery.setSort(qb.sort()
    .byScore()
    .andByField("contactType")
    .createSort());

This may not be a very elegant, or optimized solution, but I think it will work.

To customize the relative order of contact types, I would suggest a different approach: use a custom bridge to index numbers instead of the "PBX"/"TEL"/etc., assigning to each contact type the ordinal you expect. Essentially something like that:

public class Establishment {

@Field(name = "contactType_sort", bridge = @FieldBridge(impl = ContactTypeOrdinalBridge.class))
private ContactType contactType;

}

public class ContactTypeOrdinalBridge implements MetadataProvidingFieldBridge {

    @Override
    public void set(String name, Object value, Document document, LuceneOptions luceneOptions) {
        if ( value != null ) {
          int ordinal = getOrdinal((ContactType) value);
          luceneOptions.addNumericFieldToDocument(name, ordinal, document);
          luceneOptions.addNumericDocValuesFieldToDocument(name, ordinal, document);
        }
    }


    @Override
    public void configureFieldMetadata(String name, FieldMetadataBuilder builder) {
        builder.field(name, FieldType.INTEGER).sortable(true);
    }

    private int getOrdinal(ContactType value) {
        switch( value ) {
          case PBX: return 0;
          case TEL: return 1;
          case GSM: return 2;
          case PBX: return 3;
          default: return 4;
        }
    }
}

Then reindex, and sort like this:

fullTextQuery.setSort(qb.sort()
    .byScore()
    .andByField("contactType_sort")
    .createSort());
7
  • Thanks for the detailed answer. I am getting the following error after applied sort on contactType(note: i am using hibernate seach 5.10): java.lang.IllegalStateException: unexpected docvalues type NONE for field 'contactType.name' (expected=NUMERIC). Use UninvertingReader or index with docvalues. Jan 14, 2020 at 10:27
  • @KamranUllah You need to mark your field as sortable. Use @SortableField(forField = "name").
    – yrodiere
    Jan 14, 2020 at 11:01
  • I am still getting the same error. let me show you my settings: ContactType Entity: @SortableField(forField = "name") @Field(store =Store.YES, bridge = @FieldBridge(impl = ContactTypeComparator.class)) @Column(name = "NAME") private String name; Establishment Entity: @IndexedEmbedded(prefix = "contactType.", includePaths = {"id", "name"}) @ManyToOne @JoinColumn(name = "CONTACT_TYPE") private ContactTypeEntity contactType; Query: query.setSort(queryBuilder.sort().byScore().andByField("contactType.name").createSort()); Jan 14, 2020 at 12:36
  • Now when i have commented the line query.setSort(queryBuilder.sort().byScore().andByField("contactType.name").createSort());, it throwing HSEARCH000324: The fieldBridge for field 'contactType.name' is an instance of 'class ae.etisalat.dq.common.ContactTypeComparator', which does not implement TwoWayFieldBridge. Projected fields must have a TwoWayFieldBridge. Jan 14, 2020 at 14:52
  • I am using projection as: query.setProjection("id", "establishmentNameEn", "contactType.name", ...); I am showing contactType.name as PBX,TEL etc on UI instead of numbers. I have also used TwoWayFieldBridge inteface and its method as: @Override public Object get(String name, Document document) { return document.get( name ); } but the error still exists. Jan 15, 2020 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.