转贴请声明原文:solr的随机排序
有这样的一种需求,想从索引库里随机取出4条记录。
在 schema.xml:配置一个动态字段,如下。具体实现可以看代码 org.apache.solr.schema.RandomSortField
<types>
...
<fieldType name="random" class="solr.RandomSortField" />
...
</types>
<fields>
...
<dynamicField name="rand*" type="random" indexed="true" stored="false"/>
...
</fields>
由用户请求的时候按照一个动态字段排序,sort=rand_123456*类似,随机的生成,跟该动态字段有关
Examples of queries:
- http://localhost:8983/solr/select/?q=*:*&fl=name&sort=rand_1234%20desc
- http://localhost:8983/solr/select/?q=*:*&fl=name&sort=rand_2345%20desc
- http://localhost:8983/solr/select/?q=*:*&fl=name&sort=rand_ABDC%20desc
- http://localhost:8983/solr/select/?q=*:*&fl=name&sort=rand_21%20desc
同一个url 返回的结果会是相同
该字段实现自定义的一个比较器, 随机性跟传进来的动态字段名有关:主要的hash算法实现如下:
private static int getSeed(String fieldName, AtomicReaderContext context) {
final DirectoryReader top = (DirectoryReader) ReaderUtil.getTopLevelContext(context).reader();
return fieldName.hashCode() + context.docBase + (int)top.getVersion();
}
private static int hash(int key) {
key = ~key + (key << 15); // key = (key << 15) - key - 1;
key = key ^ (key >>> 12);
key = key + (key << 2);
key = key ^ (key >>> 4);
key = key * 2057; // key = (key + (key << 3)) + (key << 11);
key = key ^ (key >>> 16);
return key >>> 1;
}
原文:http://blog.youkuaiyun.com/duck_genuine/article/details/8477336
<a href="https://plus.google.com/110033444156027673423?rel=author">Google</a>