8

Not a generic sort field, but say a list of document IDs I want returned in that order.

Example: document_ids = [5, 3, 10, 6]

Can I query solr for documents 5, 3, 10, 6 in that order?

dalore
  • 5,594
  • 1
  • 36
  • 38

2 Answers2

9

Using Boost Query

You can use the bq param (Boost Query) for this and then sort by score, which is default.

q=id:5+OR+id:3+OR+id:10+OR+id:6&bq=id:5^4+id:3^3+id:10^2

As you can see within the bq parameter each of the IDs gets a declining boost value, until the last one - in your case 6 - does not receive any boost any more. Since you search by ID, each document would have the same score, so boosting them that way will get you the sort order you want.

Some reference about the parameter

Using Term Boosting

In case you are using the Standard Request Handler or the (e)DisMax this works in any case

q=id:5^4+OR+id:3^3+OR+id:10^2+OR+id:6

This makes use of Term Boosting, which is explained in the reference documentation below the topic Boosting a Term with ^. The logic keeps the same as above.

cheffe
  • 9,345
  • 2
  • 46
  • 57
  • This works with (e)dismax, but not with the standard lucene handler. – arun Nov 07 '13 at 18:28
  • 4
    Nice. A simpler syntax is `q=id:(5^4 3^3 10^2 6)` assuming default Boolean op is OR – arun Nov 07 '13 at 23:25
  • This didn't work for me. I checked my Solr results in http://explain.solr.pl/ and I can see that sometimes lower values such as `^10` gets higher scores than `^19` for instance. In this link https://wiki.apache.org/solr/SolrRelevancyCookbook#Ranking_Terms we can see it suggests using a very high boost value, but that will lead to huge queries if you need to use a lot of elements. – qxlab Jul 15 '16 at 17:24
  • 1
    Instead of using this, consider using QueryElevationComponent for those use cases. It also allows you to specify the identifiers in query time as param: https://lucene.apache.org/solr/guide/6_6/the-query-elevation-component.html#:~:text=The%20Query%20Elevation%20Component%20lets,configured%20map%20of%20top%20results. – Samuel García Aug 27 '20 at 12:12
  • @SamuelGarcía I am not working actively with Solr anymore. If you can provide a better solution, please provide an answer. – cheffe Sep 01 '20 at 09:56
0

Instead of boosts, Solr supports ConstantScore with the ^= operator. It basically assigns the specified constant score to any matching documents which is desirable when you only care about matches for a particular clause and don’t want other relevancy factors such as term frequency. So you can simply get your desired order by specifying a descending constant score for the ids in the query.

q=id:(id1^=4 OR id2^=3 OR id3^=2 OR id4^=1)

This will assign a constant score of 4 to a document with id=id1 (so it will come first), a score of 3 to a document with id=id2, etc.

Ahmad Abdelghany
  • 11,983
  • 5
  • 41
  • 36