Order by an expression in Solr

2019-02-17 07:07发布

问题:

In SQL you can order by an expression like:

SELECT * FROM a
ORDER BY CASE WHEN a.Category = 20 THEN 1 ELSE 0 DESC

so records who have Category = 20 are on top.

Is this possible in Solr?

回答1:

Solr doesn't have an if/then (at least not until 4.0), but it does have a map function and the ability to use function queries in your sort. You can probably use something like this in your sort to achieve what you're after:

 ?q=*&sort=map(category,20,20,case,0),score desc

(untested)

Here is a thread that talks about using map for an if statement.



回答2:

If you are using the dismax request handler, then you can use boost queries in a similar fashion. http://wiki.apache.org/solr/DisMaxQParserPlugin#bq_.28Boost_Query.29 Note that this doesn't function exactly like the your SQL example, but you can achieve the same results with it.



回答3:

I've accepted hross's answer, but it's also possible to do something like this in Solr 1.3 and up, using:

/select?q={!func}map(Category,20,20,1,0)&sort=score desc

The cool thing is that you can still sort on other fields, so:

&sort=score desc, name asc


标签: solr