java Lucene 中自定义排序的实现
程序员文章站
2023-12-02 19:37:40
lucene中的自定义排序功能和java集合中的自定义排序的实现方法差不多,都要实现一下比较接口. 在java中只要实现comparable接口就可以了.但是在lucene...
lucene中的自定义排序功能和java集合中的自定义排序的实现方法差不多,都要实现一下比较接口. 在java中只要实现comparable接口就可以了.但是在lucene中要实现sortcomparatorsource接口和scoredoccomparator接口.在了解具体实现方法之前先来看看这两个接口的定义吧.
sortcomparatorsource接口的功能是返回一个用来排序scoredocs的comparator(expert: returns a comparator for sorting scoredocs).该接口只定义了一个方法.如下:
java代码
/**
* creates a comparator for the field in the given index.
* @param reader - index to create comparator for.
* @param fieldname - field to create comparator for.
* @return comparator of scoredoc objects.
* @throws ioexception - if an error occurs reading the index.
*/
public scoredoccomparator newcomparator(indexreader reader,string fieldname) throws ioexception
view plaincopy to clipboardprint?
/**
* creates a comparator for the field in the given index.
* @param reader - index to create comparator for.
* @param fieldname - field to create comparator for.
* @return comparator of scoredoc objects.
* @throws ioexception - if an error occurs reading the index.
*/
public scoredoccomparator newcomparator(indexreader reader,string fieldname) throws ioexception
/**
* creates a comparator for the field in the given index.
* @param reader - index to create comparator for.
* @param fieldname - field to create comparator for.
* @return comparator of scoredoc objects.
* @throws ioexception - if an error occurs reading the index.
*/
public scoredoccomparator newcomparator(indexreader reader,string fieldname) throws ioexception
该方法只是创造一个scoredoccomparator 实例用来实现排序.所以我们还要实现scoredoccomparator 接口.来看看scoredoccomparator 接口.功能是比较来两个scoredoc 对象来排序(compares two scoredoc objects for sorting) 里面定义了两个lucene实现的静态实例.如下:
java代码
//special comparator for sorting hits according to computed relevance (document score).
public static final scoredoccomparator relevance;
//special comparator for sorting hits according to index order (document number).
public static final scoredoccomparator indexorder;
view plaincopy to clipboardprint?
//special comparator for sorting hits according to computed relevance (document score).
public static final scoredoccomparator relevance;
//special comparator for sorting hits according to index order (document number).
public static final scoredoccomparator indexorder;
//special comparator for sorting hits according to computed relevance (document score).
public static final scoredoccomparator relevance;
//special comparator for sorting hits according to index order (document number).
public static final scoredoccomparator indexorder;
有3个方法与排序相关,需要我们实现 分别如下:
java代码
/**
* compares two scoredoc objects and returns a result indicating their sort order.
* @param i first scoredoc
* @param j second scoredoc
* @return -1 if i should come before j;
* 1 if i should come after j;
* 0 if they are equal
*/
public int compare(scoredoc i,scoredoc j);
/**
* returns the value used to sort the given document. the object returned must implement the java.io.serializable interface. this is used by multisearchers to determine how to collate results from their searchers.
* @param i document
* @return serializable object
*/
public comparable sortvalue(scoredoc i);
/**
* returns the type of sort. should return sortfield.score, sortfield.doc, sortfield.string, sortfield.integer, sortfield.float or sortfield.custom. it is not valid to return sortfield.auto. this is used by multisearchers to determine how to collate results from their searchers.
* @return one of the constants in sortfield.
*/
public int sorttype();
view plaincopy to clipboardprint?
/**
* compares two scoredoc objects and returns a result indicating their sort order.
* @param i first scoredoc
* @param j second scoredoc
* @return -1 if i should come before j;
* 1 if i should come after j;
* 0 if they are equal
*/
public int compare(scoredoc i,scoredoc j);
/**
* returns the value used to sort the given document. the object returned must implement the java.io.serializable interface. this is used by multisearchers to determine how to collate results from their searchers.
* @param i document
* @return serializable object
*/
public comparable sortvalue(scoredoc i);
/**
* returns the type of sort. should return sortfield.score, sortfield.doc, sortfield.string, sortfield.integer, sortfield.float or sortfield.custom. it is not valid to return sortfield.auto. this is used by multisearchers to determine how to collate results from their searchers.
* @return one of the constants in sortfield.
*/
public int sorttype();
/**
* compares two scoredoc objects and returns a result indicating their sort order.
* @param i first scoredoc
* @param j second scoredoc
* @return -1 if i should come before j;
* 1 if i should come after j;
* 0 if they are equal
*/
public int compare(scoredoc i,scoredoc j);
/**
* returns the value used to sort the given document. the object returned must implement the java.io.serializable interface. this is used by multisearchers to determine how to collate results from their searchers.
* @param i document
* @return serializable object
*/
public comparable sortvalue(scoredoc i);
/**
* returns the type of sort. should return sortfield.score, sortfield.doc, sortfield.string, sortfield.integer, sortfield.float or sortfield.custom. it is not valid to return sortfield.auto. this is used by multisearchers to determine how to collate results from their searchers.
* @return one of the constants in sortfield.
*/
public int sorttype();
看个例子吧!
该例子为lucene in action中的一个实现,用来搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储.
java代码
package com.nikee.lucene;
import java.io.ioexception;
import org.apache.lucene.index.indexreader;
import org.apache.lucene.index.term;
import org.apache.lucene.index.termdocs;
import org.apache.lucene.index.termenum;
import org.apache.lucene.search.scoredoc;
import org.apache.lucene.search.scoredoccomparator;
import org.apache.lucene.search.sortcomparatorsource;
import org.apache.lucene.search.sortfield;
//实现了搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储
//distancecomparatorsource 实现了sortcomparatorsource接口
public class distancecomparatorsource implements sortcomparatorsource {
private static final long serialversionuid = 1l;
// x y 用来保存 坐标位置
private int x;
private int y;
public distancecomparatorsource(int x, int y) {
this.x = x;
this.y = y;
}
// 返回scoredoccomparator 用来实现排序功能
public scoredoccomparator newcomparator(indexreader reader, string fieldname) throws ioexception {
return new distancescoredoclookupcomparator(reader, fieldname, x, y);
}
//distancescoredoclookupcomparator 实现了scoredoccomparator 用来排序
private static class distancescoredoclookupcomparator implements scoredoccomparator {
private float[] distances; // 保存每个餐馆到指定点的距离
// 构造函数 , 构造函数在这里几乎完成所有的准备工作.
public distancescoredoclookupcomparator(indexreader reader, string fieldname, int x, int y) throws ioexception {
system.out.println("fieldname2="+fieldname);
final termenum enumerator = reader.terms(new term(fieldname, ""));
system.out.println("maxdoc="+reader.maxdoc());
distances = new float[reader.maxdoc()]; // 初始化distances
if (distances.length > 0) {
termdocs termdocs = reader.termdocs();
try {
if (enumerator.term() == null) {
throw new runtimeexception("no terms in field " + fieldname);
}
int i = 0,j = 0;
do {
system.out.println("in do-while :" + i ++);
term term = enumerator.term(); // 取出每一个term
if (term.field() != fieldname) // 与给定的域不符合则比较下一个
break;
//sets this to the data for the current term in a termenum.
//this may be optimized in some implementations.
termdocs.seek(enumerator); //参考termdocs doc
while (termdocs.next()) {
system.out.println(" in while :" + j ++);
system.out.println(" in while ,term :" + term.tostring());
string[] xy = term.text().split(","); // 去处x y
int deltax = integer.parseint(xy[0]) - x;
int deltay = integer.parseint(xy[1]) - y;
// 计算距离
distances[termdocs.doc()] = (float) math.sqrt(deltax * deltax + deltay * deltay);
}
}
while (enumerator.next());
} finally {
termdocs.close();
}
}
}
//有上面的构造函数的准备 这里就比较简单了
public int compare(scoredoc i, scoredoc j) {
if (distances[i.doc] < distances[j.doc])
return -1;
if (distances[i.doc] > distances[j.doc])
return 1;
return 0;
}
// 返回距离
public comparable sortvalue(scoredoc i) {
return new float(distances[i.doc]);
}
//指定sorttype
public int sorttype() {
return sortfield.float;
}
}
public string tostring() {
return "distance from (" + x + "," + y + ")";
}
}
view plaincopy to clipboardprint?
package com.nikee.lucene;
import java.io.ioexception;
import org.apache.lucene.index.indexreader;
import org.apache.lucene.index.term;
import org.apache.lucene.index.termdocs;
import org.apache.lucene.index.termenum;
import org.apache.lucene.search.scoredoc;
import org.apache.lucene.search.scoredoccomparator;
import org.apache.lucene.search.sortcomparatorsource;
import org.apache.lucene.search.sortfield;
//实现了搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储
//distancecomparatorsource 实现了sortcomparatorsource接口
public class distancecomparatorsource implements sortcomparatorsource {
private static final long serialversionuid = 1l;
// x y 用来保存 坐标位置
private int x;
private int y;
public distancecomparatorsource(int x, int y) {
this.x = x;
this.y = y;
}
// 返回scoredoccomparator 用来实现排序功能
public scoredoccomparator newcomparator(indexreader reader, string fieldname) throws ioexception {
return new distancescoredoclookupcomparator(reader, fieldname, x, y);
}
//distancescoredoclookupcomparator 实现了scoredoccomparator 用来排序
private static class distancescoredoclookupcomparator implements scoredoccomparator {
private float[] distances; // 保存每个餐馆到指定点的距离
// 构造函数 , 构造函数在这里几乎完成所有的准备工作.
public distancescoredoclookupcomparator(indexreader reader, string fieldname, int x, int y) throws ioexception {
system.out.println("fieldname2="+fieldname);
final termenum enumerator = reader.terms(new term(fieldname, ""));
system.out.println("maxdoc="+reader.maxdoc());
distances = new float[reader.maxdoc()]; // 初始化distances
if (distances.length > 0) {
termdocs termdocs = reader.termdocs();
try {
if (enumerator.term() == null) {
throw new runtimeexception("no terms in field " + fieldname);
}
int i = 0,j = 0;
do {
system.out.println("in do-while :" + i ++);
term term = enumerator.term(); // 取出每一个term
if (term.field() != fieldname) // 与给定的域不符合则比较下一个
break;
//sets this to the data for the current term in a termenum.
//this may be optimized in some implementations.
termdocs.seek(enumerator); //参考termdocs doc
while (termdocs.next()) {
system.out.println(" in while :" + j ++);
system.out.println(" in while ,term :" + term.tostring());
string[] xy = term.text().split(","); // 去处x y
int deltax = integer.parseint(xy[0]) - x;
int deltay = integer.parseint(xy[1]) - y;
// 计算距离
distances[termdocs.doc()] = (float) math.sqrt(deltax * deltax + deltay * deltay);
}
}
while (enumerator.next());
} finally {
termdocs.close();
}
}
}
//有上面的构造函数的准备 这里就比较简单了
public int compare(scoredoc i, scoredoc j) {
if (distances[i.doc] < distances[j.doc])
return -1;
if (distances[i.doc] > distances[j.doc])
return 1;
return 0;
}
// 返回距离
public comparable sortvalue(scoredoc i) {
return new float(distances[i.doc]);
}
//指定sorttype
public int sorttype() {
return sortfield.float;
}
}
public string tostring() {
return "distance from (" + x + "," + y + ")";
}
}
package com.nikee.lucene;
import java.io.ioexception;
import org.apache.lucene.index.indexreader;
import org.apache.lucene.index.term;
import org.apache.lucene.index.termdocs;
import org.apache.lucene.index.termenum;
import org.apache.lucene.search.scoredoc;
import org.apache.lucene.search.scoredoccomparator;
import org.apache.lucene.search.sortcomparatorsource;
import org.apache.lucene.search.sortfield;
//实现了搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储
//distancecomparatorsource 实现了sortcomparatorsource接口
public class distancecomparatorsource implements sortcomparatorsource {
private static final long serialversionuid = 1l;
// x y 用来保存 坐标位置
private int x;
private int y;
public distancecomparatorsource(int x, int y) {
this.x = x;
this.y = y;
}
// 返回scoredoccomparator 用来实现排序功能
public scoredoccomparator newcomparator(indexreader reader, string fieldname) throws ioexception {
return new distancescoredoclookupcomparator(reader, fieldname, x, y);
}
//distancescoredoclookupcomparator 实现了scoredoccomparator 用来排序
private static class distancescoredoclookupcomparator implements scoredoccomparator {
private float[] distances; // 保存每个餐馆到指定点的距离
// 构造函数 , 构造函数在这里几乎完成所有的准备工作.
public distancescoredoclookupcomparator(indexreader reader, string fieldname, int x, int y) throws ioexception {
system.out.println("fieldname2="+fieldname);
final termenum enumerator = reader.terms(new term(fieldname, ""));
system.out.println("maxdoc="+reader.maxdoc());
distances = new float[reader.maxdoc()]; // 初始化distances
if (distances.length > 0) {
termdocs termdocs = reader.termdocs();
try {
if (enumerator.term() == null) {
throw new runtimeexception("no terms in field " + fieldname);
}
int i = 0,j = 0;
do {
system.out.println("in do-while :" + i ++);
term term = enumerator.term(); // 取出每一个term
if (term.field() != fieldname) // 与给定的域不符合则比较下一个
break;
//sets this to the data for the current term in a termenum.
//this may be optimized in some implementations.
termdocs.seek(enumerator); //参考termdocs doc
while (termdocs.next()) {
system.out.println(" in while :" + j ++);
system.out.println(" in while ,term :" + term.tostring());
string[] xy = term.text().split(","); // 去处x y
int deltax = integer.parseint(xy[0]) - x;
int deltay = integer.parseint(xy[1]) - y;
// 计算距离
distances[termdocs.doc()] = (float) math.sqrt(deltax * deltax + deltay * deltay);
}
}
while (enumerator.next());
} finally {
termdocs.close();
}
}
}
//有上面的构造函数的准备 这里就比较简单了
public int compare(scoredoc i, scoredoc j) {
if (distances[i.doc] < distances[j.doc])
return -1;
if (distances[i.doc] > distances[j.doc])
return 1;
return 0;
}
// 返回距离
public comparable sortvalue(scoredoc i) {
return new float(distances[i.doc]);
}
//指定sorttype
public int sorttype() {
return sortfield.float;
}
}
public string tostring() {
return "distance from (" + x + "," + y + ")";
}
}
这是一个实现了上面两个接口的两个类, 里面带有详细注释, 可以看出 自定义排序并不是很难的. 该实现能否正确实现,我们来看看测试代码能否通过吧.
java代码
package com.nikee.lucene.test;
import java.io.ioexception;
import junit.framework.testcase;
import org.apache.lucene.analysis.whitespaceanalyzer;
import org.apache.lucene.document.document;
import org.apache.lucene.document.field;
import org.apache.lucene.index.indexwriter;
import org.apache.lucene.index.term;
import org.apache.lucene.search.fielddoc;
import org.apache.lucene.search.hits;
import org.apache.lucene.search.indexsearcher;
import org.apache.lucene.search.query;
import org.apache.lucene.search.scoredoc;
import org.apache.lucene.search.sort;
import org.apache.lucene.search.sortfield;
import org.apache.lucene.search.termquery;
import org.apache.lucene.search.topfielddocs;
import org.apache.lucene.store.ramdirectory;
import com.nikee.lucene.distancecomparatorsource;
public class distancecomparatorsourcetest extends testcase {
private ramdirectory directory;
private indexsearcher searcher;
private query query;
//建立测试环境
protected void setup() throws exception {
directory = new ramdirectory();
indexwriter writer = new indexwriter(directory, new whitespaceanalyzer(), true);
addpoint(writer, "el charro", "restaurant", 1, 2);
addpoint(writer, "cafe poca cosa", "restaurant", 5, 9);
addpoint(writer, "los betos", "restaurant", 9, 6);
addpoint(writer, "nico's taco shop", "restaurant", 3, 8);
writer.close();
searcher = new indexsearcher(directory);
query = new termquery(new term("type", "restaurant"));
}
private void addpoint(indexwriter writer, string name, string type, int x, int y) throws ioexception {
document doc = new document();
doc.add(new field("name", name, field.store.yes, field.index.tokenized));
doc.add(new field("type", type, field.store.yes, field.index.tokenized));
doc.add(new field("location", x + "," + y, field.store.yes, field.index.un_tokenized));
writer.adddocument(doc);
}
public void testnearestrestauranttohome() throws exception {
//使用distancecomparatorsource来构造一个sortfield
sort sort = new sort(new sortfield("location", new distancecomparatorsource(0, 0)));
hits hits = searcher.search(query, sort); // 搜索
//测试
assertequals("closest", "el charro", hits.doc(0).get("name"));
assertequals("furthest", "los betos", hits.doc(3).get("name"));
}
public void testneareastrestauranttowork() throws exception {
sort sort = new sort(new sortfield("location", new distancecomparatorsource(10, 10))); // 工作的坐标 10,10
//上面的测试实现了自定义排序,但是并不能访问自定义排序的更详细信息,利用
//topfielddocs 可以进一步访问相关信息
topfielddocs docs = searcher.search(query, null, 3, sort);
assertequals(4, docs.totalhits);
assertequals(3, docs.scoredocs.length);
//取得fielddoc 利用fielddoc可以取得关于排序的更详细信息 请查看fielddoc doc
fielddoc fielddoc = (fielddoc) docs.scoredocs[0];
assertequals("(10,10) -> (9,6) = sqrt(17)", new float(math.sqrt(17)), fielddoc.fields[0]);
document document = searcher.doc(fielddoc.doc);
assertequals("los betos", document.get("name"));
dumpdocs(sort, docs); // 显示相关信息
}
// 显示有关排序的信息
private void dumpdocs(sort sort, topfielddocs docs) throws ioexception {
system.out.println("sorted by: " + sort);
scoredoc[] scoredocs = docs.scoredocs;
for (int i = 0; i < scoredocs.length; i++) {
fielddoc fielddoc = (fielddoc) scoredocs[i];
float distance = (float) fielddoc.fields[0];
document doc = searcher.doc(fielddoc.doc);
system.out.println(" " + doc.get("name") + " @ (" + doc.get("location") + ") -> " + distance);
}
}
}
sortcomparatorsource接口的功能是返回一个用来排序scoredocs的comparator(expert: returns a comparator for sorting scoredocs).该接口只定义了一个方法.如下:
java代码
/**
* creates a comparator for the field in the given index.
* @param reader - index to create comparator for.
* @param fieldname - field to create comparator for.
* @return comparator of scoredoc objects.
* @throws ioexception - if an error occurs reading the index.
*/
public scoredoccomparator newcomparator(indexreader reader,string fieldname) throws ioexception
view plaincopy to clipboardprint?
/**
* creates a comparator for the field in the given index.
* @param reader - index to create comparator for.
* @param fieldname - field to create comparator for.
* @return comparator of scoredoc objects.
* @throws ioexception - if an error occurs reading the index.
*/
public scoredoccomparator newcomparator(indexreader reader,string fieldname) throws ioexception
/**
* creates a comparator for the field in the given index.
* @param reader - index to create comparator for.
* @param fieldname - field to create comparator for.
* @return comparator of scoredoc objects.
* @throws ioexception - if an error occurs reading the index.
*/
public scoredoccomparator newcomparator(indexreader reader,string fieldname) throws ioexception
该方法只是创造一个scoredoccomparator 实例用来实现排序.所以我们还要实现scoredoccomparator 接口.来看看scoredoccomparator 接口.功能是比较来两个scoredoc 对象来排序(compares two scoredoc objects for sorting) 里面定义了两个lucene实现的静态实例.如下:
java代码
//special comparator for sorting hits according to computed relevance (document score).
public static final scoredoccomparator relevance;
//special comparator for sorting hits according to index order (document number).
public static final scoredoccomparator indexorder;
view plaincopy to clipboardprint?
//special comparator for sorting hits according to computed relevance (document score).
public static final scoredoccomparator relevance;
//special comparator for sorting hits according to index order (document number).
public static final scoredoccomparator indexorder;
//special comparator for sorting hits according to computed relevance (document score).
public static final scoredoccomparator relevance;
//special comparator for sorting hits according to index order (document number).
public static final scoredoccomparator indexorder;
有3个方法与排序相关,需要我们实现 分别如下:
java代码
/**
* compares two scoredoc objects and returns a result indicating their sort order.
* @param i first scoredoc
* @param j second scoredoc
* @return -1 if i should come before j;
* 1 if i should come after j;
* 0 if they are equal
*/
public int compare(scoredoc i,scoredoc j);
/**
* returns the value used to sort the given document. the object returned must implement the java.io.serializable interface. this is used by multisearchers to determine how to collate results from their searchers.
* @param i document
* @return serializable object
*/
public comparable sortvalue(scoredoc i);
/**
* returns the type of sort. should return sortfield.score, sortfield.doc, sortfield.string, sortfield.integer, sortfield.float or sortfield.custom. it is not valid to return sortfield.auto. this is used by multisearchers to determine how to collate results from their searchers.
* @return one of the constants in sortfield.
*/
public int sorttype();
view plaincopy to clipboardprint?
/**
* compares two scoredoc objects and returns a result indicating their sort order.
* @param i first scoredoc
* @param j second scoredoc
* @return -1 if i should come before j;
* 1 if i should come after j;
* 0 if they are equal
*/
public int compare(scoredoc i,scoredoc j);
/**
* returns the value used to sort the given document. the object returned must implement the java.io.serializable interface. this is used by multisearchers to determine how to collate results from their searchers.
* @param i document
* @return serializable object
*/
public comparable sortvalue(scoredoc i);
/**
* returns the type of sort. should return sortfield.score, sortfield.doc, sortfield.string, sortfield.integer, sortfield.float or sortfield.custom. it is not valid to return sortfield.auto. this is used by multisearchers to determine how to collate results from their searchers.
* @return one of the constants in sortfield.
*/
public int sorttype();
/**
* compares two scoredoc objects and returns a result indicating their sort order.
* @param i first scoredoc
* @param j second scoredoc
* @return -1 if i should come before j;
* 1 if i should come after j;
* 0 if they are equal
*/
public int compare(scoredoc i,scoredoc j);
/**
* returns the value used to sort the given document. the object returned must implement the java.io.serializable interface. this is used by multisearchers to determine how to collate results from their searchers.
* @param i document
* @return serializable object
*/
public comparable sortvalue(scoredoc i);
/**
* returns the type of sort. should return sortfield.score, sortfield.doc, sortfield.string, sortfield.integer, sortfield.float or sortfield.custom. it is not valid to return sortfield.auto. this is used by multisearchers to determine how to collate results from their searchers.
* @return one of the constants in sortfield.
*/
public int sorttype();
看个例子吧!
该例子为lucene in action中的一个实现,用来搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储.
java代码
package com.nikee.lucene;
import java.io.ioexception;
import org.apache.lucene.index.indexreader;
import org.apache.lucene.index.term;
import org.apache.lucene.index.termdocs;
import org.apache.lucene.index.termenum;
import org.apache.lucene.search.scoredoc;
import org.apache.lucene.search.scoredoccomparator;
import org.apache.lucene.search.sortcomparatorsource;
import org.apache.lucene.search.sortfield;
//实现了搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储
//distancecomparatorsource 实现了sortcomparatorsource接口
public class distancecomparatorsource implements sortcomparatorsource {
private static final long serialversionuid = 1l;
// x y 用来保存 坐标位置
private int x;
private int y;
public distancecomparatorsource(int x, int y) {
this.x = x;
this.y = y;
}
// 返回scoredoccomparator 用来实现排序功能
public scoredoccomparator newcomparator(indexreader reader, string fieldname) throws ioexception {
return new distancescoredoclookupcomparator(reader, fieldname, x, y);
}
//distancescoredoclookupcomparator 实现了scoredoccomparator 用来排序
private static class distancescoredoclookupcomparator implements scoredoccomparator {
private float[] distances; // 保存每个餐馆到指定点的距离
// 构造函数 , 构造函数在这里几乎完成所有的准备工作.
public distancescoredoclookupcomparator(indexreader reader, string fieldname, int x, int y) throws ioexception {
system.out.println("fieldname2="+fieldname);
final termenum enumerator = reader.terms(new term(fieldname, ""));
system.out.println("maxdoc="+reader.maxdoc());
distances = new float[reader.maxdoc()]; // 初始化distances
if (distances.length > 0) {
termdocs termdocs = reader.termdocs();
try {
if (enumerator.term() == null) {
throw new runtimeexception("no terms in field " + fieldname);
}
int i = 0,j = 0;
do {
system.out.println("in do-while :" + i ++);
term term = enumerator.term(); // 取出每一个term
if (term.field() != fieldname) // 与给定的域不符合则比较下一个
break;
//sets this to the data for the current term in a termenum.
//this may be optimized in some implementations.
termdocs.seek(enumerator); //参考termdocs doc
while (termdocs.next()) {
system.out.println(" in while :" + j ++);
system.out.println(" in while ,term :" + term.tostring());
string[] xy = term.text().split(","); // 去处x y
int deltax = integer.parseint(xy[0]) - x;
int deltay = integer.parseint(xy[1]) - y;
// 计算距离
distances[termdocs.doc()] = (float) math.sqrt(deltax * deltax + deltay * deltay);
}
}
while (enumerator.next());
} finally {
termdocs.close();
}
}
}
//有上面的构造函数的准备 这里就比较简单了
public int compare(scoredoc i, scoredoc j) {
if (distances[i.doc] < distances[j.doc])
return -1;
if (distances[i.doc] > distances[j.doc])
return 1;
return 0;
}
// 返回距离
public comparable sortvalue(scoredoc i) {
return new float(distances[i.doc]);
}
//指定sorttype
public int sorttype() {
return sortfield.float;
}
}
public string tostring() {
return "distance from (" + x + "," + y + ")";
}
}
view plaincopy to clipboardprint?
package com.nikee.lucene;
import java.io.ioexception;
import org.apache.lucene.index.indexreader;
import org.apache.lucene.index.term;
import org.apache.lucene.index.termdocs;
import org.apache.lucene.index.termenum;
import org.apache.lucene.search.scoredoc;
import org.apache.lucene.search.scoredoccomparator;
import org.apache.lucene.search.sortcomparatorsource;
import org.apache.lucene.search.sortfield;
//实现了搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储
//distancecomparatorsource 实现了sortcomparatorsource接口
public class distancecomparatorsource implements sortcomparatorsource {
private static final long serialversionuid = 1l;
// x y 用来保存 坐标位置
private int x;
private int y;
public distancecomparatorsource(int x, int y) {
this.x = x;
this.y = y;
}
// 返回scoredoccomparator 用来实现排序功能
public scoredoccomparator newcomparator(indexreader reader, string fieldname) throws ioexception {
return new distancescoredoclookupcomparator(reader, fieldname, x, y);
}
//distancescoredoclookupcomparator 实现了scoredoccomparator 用来排序
private static class distancescoredoclookupcomparator implements scoredoccomparator {
private float[] distances; // 保存每个餐馆到指定点的距离
// 构造函数 , 构造函数在这里几乎完成所有的准备工作.
public distancescoredoclookupcomparator(indexreader reader, string fieldname, int x, int y) throws ioexception {
system.out.println("fieldname2="+fieldname);
final termenum enumerator = reader.terms(new term(fieldname, ""));
system.out.println("maxdoc="+reader.maxdoc());
distances = new float[reader.maxdoc()]; // 初始化distances
if (distances.length > 0) {
termdocs termdocs = reader.termdocs();
try {
if (enumerator.term() == null) {
throw new runtimeexception("no terms in field " + fieldname);
}
int i = 0,j = 0;
do {
system.out.println("in do-while :" + i ++);
term term = enumerator.term(); // 取出每一个term
if (term.field() != fieldname) // 与给定的域不符合则比较下一个
break;
//sets this to the data for the current term in a termenum.
//this may be optimized in some implementations.
termdocs.seek(enumerator); //参考termdocs doc
while (termdocs.next()) {
system.out.println(" in while :" + j ++);
system.out.println(" in while ,term :" + term.tostring());
string[] xy = term.text().split(","); // 去处x y
int deltax = integer.parseint(xy[0]) - x;
int deltay = integer.parseint(xy[1]) - y;
// 计算距离
distances[termdocs.doc()] = (float) math.sqrt(deltax * deltax + deltay * deltay);
}
}
while (enumerator.next());
} finally {
termdocs.close();
}
}
}
//有上面的构造函数的准备 这里就比较简单了
public int compare(scoredoc i, scoredoc j) {
if (distances[i.doc] < distances[j.doc])
return -1;
if (distances[i.doc] > distances[j.doc])
return 1;
return 0;
}
// 返回距离
public comparable sortvalue(scoredoc i) {
return new float(distances[i.doc]);
}
//指定sorttype
public int sorttype() {
return sortfield.float;
}
}
public string tostring() {
return "distance from (" + x + "," + y + ")";
}
}
package com.nikee.lucene;
import java.io.ioexception;
import org.apache.lucene.index.indexreader;
import org.apache.lucene.index.term;
import org.apache.lucene.index.termdocs;
import org.apache.lucene.index.termenum;
import org.apache.lucene.search.scoredoc;
import org.apache.lucene.search.scoredoccomparator;
import org.apache.lucene.search.sortcomparatorsource;
import org.apache.lucene.search.sortfield;
//实现了搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储
//distancecomparatorsource 实现了sortcomparatorsource接口
public class distancecomparatorsource implements sortcomparatorsource {
private static final long serialversionuid = 1l;
// x y 用来保存 坐标位置
private int x;
private int y;
public distancecomparatorsource(int x, int y) {
this.x = x;
this.y = y;
}
// 返回scoredoccomparator 用来实现排序功能
public scoredoccomparator newcomparator(indexreader reader, string fieldname) throws ioexception {
return new distancescoredoclookupcomparator(reader, fieldname, x, y);
}
//distancescoredoclookupcomparator 实现了scoredoccomparator 用来排序
private static class distancescoredoclookupcomparator implements scoredoccomparator {
private float[] distances; // 保存每个餐馆到指定点的距离
// 构造函数 , 构造函数在这里几乎完成所有的准备工作.
public distancescoredoclookupcomparator(indexreader reader, string fieldname, int x, int y) throws ioexception {
system.out.println("fieldname2="+fieldname);
final termenum enumerator = reader.terms(new term(fieldname, ""));
system.out.println("maxdoc="+reader.maxdoc());
distances = new float[reader.maxdoc()]; // 初始化distances
if (distances.length > 0) {
termdocs termdocs = reader.termdocs();
try {
if (enumerator.term() == null) {
throw new runtimeexception("no terms in field " + fieldname);
}
int i = 0,j = 0;
do {
system.out.println("in do-while :" + i ++);
term term = enumerator.term(); // 取出每一个term
if (term.field() != fieldname) // 与给定的域不符合则比较下一个
break;
//sets this to the data for the current term in a termenum.
//this may be optimized in some implementations.
termdocs.seek(enumerator); //参考termdocs doc
while (termdocs.next()) {
system.out.println(" in while :" + j ++);
system.out.println(" in while ,term :" + term.tostring());
string[] xy = term.text().split(","); // 去处x y
int deltax = integer.parseint(xy[0]) - x;
int deltay = integer.parseint(xy[1]) - y;
// 计算距离
distances[termdocs.doc()] = (float) math.sqrt(deltax * deltax + deltay * deltay);
}
}
while (enumerator.next());
} finally {
termdocs.close();
}
}
}
//有上面的构造函数的准备 这里就比较简单了
public int compare(scoredoc i, scoredoc j) {
if (distances[i.doc] < distances[j.doc])
return -1;
if (distances[i.doc] > distances[j.doc])
return 1;
return 0;
}
// 返回距离
public comparable sortvalue(scoredoc i) {
return new float(distances[i.doc]);
}
//指定sorttype
public int sorttype() {
return sortfield.float;
}
}
public string tostring() {
return "distance from (" + x + "," + y + ")";
}
}
这是一个实现了上面两个接口的两个类, 里面带有详细注释, 可以看出 自定义排序并不是很难的. 该实现能否正确实现,我们来看看测试代码能否通过吧.
java代码
package com.nikee.lucene.test;
import java.io.ioexception;
import junit.framework.testcase;
import org.apache.lucene.analysis.whitespaceanalyzer;
import org.apache.lucene.document.document;
import org.apache.lucene.document.field;
import org.apache.lucene.index.indexwriter;
import org.apache.lucene.index.term;
import org.apache.lucene.search.fielddoc;
import org.apache.lucene.search.hits;
import org.apache.lucene.search.indexsearcher;
import org.apache.lucene.search.query;
import org.apache.lucene.search.scoredoc;
import org.apache.lucene.search.sort;
import org.apache.lucene.search.sortfield;
import org.apache.lucene.search.termquery;
import org.apache.lucene.search.topfielddocs;
import org.apache.lucene.store.ramdirectory;
import com.nikee.lucene.distancecomparatorsource;
public class distancecomparatorsourcetest extends testcase {
private ramdirectory directory;
private indexsearcher searcher;
private query query;
//建立测试环境
protected void setup() throws exception {
directory = new ramdirectory();
indexwriter writer = new indexwriter(directory, new whitespaceanalyzer(), true);
addpoint(writer, "el charro", "restaurant", 1, 2);
addpoint(writer, "cafe poca cosa", "restaurant", 5, 9);
addpoint(writer, "los betos", "restaurant", 9, 6);
addpoint(writer, "nico's taco shop", "restaurant", 3, 8);
writer.close();
searcher = new indexsearcher(directory);
query = new termquery(new term("type", "restaurant"));
}
private void addpoint(indexwriter writer, string name, string type, int x, int y) throws ioexception {
document doc = new document();
doc.add(new field("name", name, field.store.yes, field.index.tokenized));
doc.add(new field("type", type, field.store.yes, field.index.tokenized));
doc.add(new field("location", x + "," + y, field.store.yes, field.index.un_tokenized));
writer.adddocument(doc);
}
public void testnearestrestauranttohome() throws exception {
//使用distancecomparatorsource来构造一个sortfield
sort sort = new sort(new sortfield("location", new distancecomparatorsource(0, 0)));
hits hits = searcher.search(query, sort); // 搜索
//测试
assertequals("closest", "el charro", hits.doc(0).get("name"));
assertequals("furthest", "los betos", hits.doc(3).get("name"));
}
public void testneareastrestauranttowork() throws exception {
sort sort = new sort(new sortfield("location", new distancecomparatorsource(10, 10))); // 工作的坐标 10,10
//上面的测试实现了自定义排序,但是并不能访问自定义排序的更详细信息,利用
//topfielddocs 可以进一步访问相关信息
topfielddocs docs = searcher.search(query, null, 3, sort);
assertequals(4, docs.totalhits);
assertequals(3, docs.scoredocs.length);
//取得fielddoc 利用fielddoc可以取得关于排序的更详细信息 请查看fielddoc doc
fielddoc fielddoc = (fielddoc) docs.scoredocs[0];
assertequals("(10,10) -> (9,6) = sqrt(17)", new float(math.sqrt(17)), fielddoc.fields[0]);
document document = searcher.doc(fielddoc.doc);
assertequals("los betos", document.get("name"));
dumpdocs(sort, docs); // 显示相关信息
}
// 显示有关排序的信息
private void dumpdocs(sort sort, topfielddocs docs) throws ioexception {
system.out.println("sorted by: " + sort);
scoredoc[] scoredocs = docs.scoredocs;
for (int i = 0; i < scoredocs.length; i++) {
fielddoc fielddoc = (fielddoc) scoredocs[i];
float distance = (float) fielddoc.fields[0];
document doc = searcher.doc(fielddoc.doc);
system.out.println(" " + doc.get("name") + " @ (" + doc.get("location") + ") -> " + distance);
}
}
}
下一篇: MySQL常用类型转换函数总结(推荐)