Search code examples
sortingsolrlucenefull-text-searchphrase

Give advantage to search by phrase in sort SOLR


Search query which I send to SOLR is:

?q=iphone 4s&sort=sold desc

By default the search works great, but the problem appears when I want to sort results by some field for eg. sold - No. of sold products.

SOLR finds all the results which have: (iphone 4s) or (iphone) or (4s) So, when I apply sort by field 'sold' first result is: "iPhone 3GS..." which is problem.

I need the results by phrase ("iphone 4s") first and then the rest of the results - all sorted by sold.

So, the questions are:

Is it possible to have query like this, and how?

q=iphone 4s&sort={some algoritam for phrase results first} desc, sold desc

Or, can I perform this by setting up query analyzer and how?

At the moment this is solved by sending 2 requests to SOLR, first with phrase "iphone 4s" and, if this returns 0 results, I perform second request without the phrase - only: iphone 4s.


Solution

  • If sorting by score, id, field is not sufficient, Lucene lets you implement custom sorting mechanism by providing your own subclass of FieldComparatorSource abstract base class.

    With in that custom-sort-logic, you can implement the way that realizes your requirements.

    Example Java code:

    If(modelNum1.equals(modelNum2)){
    //return based on number of units sold.
    }else{
    //ALWAYS return a value such that the preferred model beats others.
    }
    

    DISCLAIMER: This may lead to maintenance problems as you will have to change the logic when a new phone model arrives.

    Steps:

    1) Sort object accepts FieldComparatorSource type instance during instantiation.

    2) Extend the FieldComparatorSource

    3) You've to load the required field information that participates in 'SORTING' using FieldCache within the FieldComparatorSource in setNextReader()

    4) Override the FieldComparatorSource.newComparator() to return your custom FieldComparator.

    5) In the method FieldComparator.compare(slot1DocId, slot2DocId), you may include your custom logic by accessing the corresponding field information, via loaded FieldCache, using the docIds passed in.

    Incorporating Lucene code into Solr as a plug-in should not trouble you..