solr FunctionQueries 通过提供一系列的函数,可以自定义查询结果排序的目的。官方提供了很多实用的函数可供实用。http://wiki.apache.org/solr/FunctionQuery
如果需要自己定义函数,那么我们需要做以下几个步骤:
1.继承org.apache.solr.search.ValueSourceParser.如下例子所示
public class MyValueSourceParser extends ValueSourceParser {
public void init(NamedList namedList) {
}
public ValueSource parse(FunctionQParser fqp) throws ParseException {
return new MyValueSource();
}
}
<valueSourceParser name="myfunc" class="com.mycompany.MyValueSourceParser" />
如何实现自己的MyValueSource?下面是官方的几个函数的例子
org.apache.solr.search.function.ConstValueSource
Example SolrQuerySyntax: _val_:1.5
这个函数的作用就是直接返回常量值,使得在bf中能直接使用常量
public class ConstValueSource extends ValueSource {
final float constant;
public ConstValueSource(float constant) {
this.constant = constant;
}
public DocValues getValues(Map context, IndexReader reader) throws IOException {
return new DocValues() {
public float floatVal(int doc) {
return constant;
}
public int intVal(int doc) {
return (int)floatVal(doc);
}
public long longVal(int doc) {
return (long)floatVal(doc);
}
public double doubleVal(int doc) {
return (double)floatVal(doc);
}
public String strVal(int doc) {
return Float.toString(floatVal(doc));
}
public String toString(int doc) {
return description();
}
};
}
// commented out some boilerplate stuff
}
org.apache.solr.search.function.OrdFieldSource
ord(myfield) returns the ordinal of the indexed field value within the indexed list of terms for that field in lucene index order (lexicographically ordered by unicode value), starting at 1. In other words, for a given field, all values are ordered lexicographically; this function then returns the offset of a particular value in that ordering.
Example SolrQuerySyntax: _val_:"ord(myIndexedField)"
public class OrdFieldSource extends ValueSource {
protected String field;
public OrdFieldSource(String field) {
this.field = field;
}
public DocValues getValues(Map context, IndexReader reader) throws IOException {
return new StringIndexDocValues(this, reader, field) {
protected String toTerm(String readableValue) {
return readableValue;
}
public float floatVal(int doc) {
return (float)order[doc];
}
public int intVal(int doc) {
return order[doc];
}
public long longVal(int doc) {
return (long)order[doc];
}
public double doubleVal(int doc) {
return (double)order[doc];
}
public String strVal(int doc) {
// the string value of the ordinal, not the string itself
return Integer.toString(order[doc]);
}
public String toString(int doc) {
return description() + '=' + intVal(doc);
}
};
}
}
OrdFieldSource 的实现方式几乎和ConstValueSource一致,主要区别在于,他返回排序后的order的索引值而不是常量。