君子博学而日参省乎己 则知明而行无过矣

博客园 首页 新随笔 联系 订阅 管理

使用Lucene来搜索内容,搜索结果的显示顺序当然是比较重要的.Lucene中Build-in的几个排序定义在大多数情况下是不适合我们使用的.要适合自己的应用程序的场景,就只能自定义排序功能,本节我们就来看看在Lucene中如何实现自定义排序功能.

     Lucene中的自定义排序功能和Java集合中的自定义排序的实现方法差不多,都要实现一下比较接口. 在Java中只要实现Comparable接口就可以了.但是在Lucene中要实现SortComparatorSource接口和 ScoreDocComparator接口.在了解具体实现方法之前先来看看这两个接口的定义吧.

    SortComparatorSource接口的功能是返回一个用来排序ScoreDocs的comparator(Expert: returns a comparator for sorting ScoreDocs).该接口只定义了一个方法.如下:

Java代码  收藏代码
  1. /**   
  2.  * Creates a comparator for the field in the given index.    
  3.  * @param reader - Index to create comparator for.    
  4.  * @param fieldname - Field to create comparator for.   
  5.  * @return Comparator of ScoreDoc objects.    
  6.  * @throws IOException - If an error occurs reading the index.    
  7.  */    
  8. public ScoreDocComparator newComparator(IndexReader reader,String fieldname) throws IOException    
  9.   
  10. /** 
  11.  * Creates a comparator for the field in the given index.  
  12.  * @param reader - Index to create comparator for.  
  13.  * @param fieldname - Field to create comparator for. 
  14.  * @return Comparator of ScoreDoc objects.  
  15.  * @throws IOException - If an error occurs reading the index.  
  16.  */  
  17. public ScoreDocComparator newComparator(IndexReader reader,String fieldname) throws IOException      


      该方法只是创造一个ScoreDocComparator 实例用来实现排序.所以我们还要实现ScoreDocComparator 接口.来看看ScoreDocComparator 接口.功能是比较来两个ScoreDoc 对象来排序(Compares two ScoreDoc objects for sorting) 里面定义了两个Lucene实现的静态实例.如下:

Java代码  收藏代码
  1.    
  2. //Special comparator for sorting hits according to computed relevance (document score).      
  3. public static final ScoreDocComparator RELEVANCE;     
  4.          
  5. //Special comparator for sorting hits according to index order (document number).      
  6. public static final ScoreDocComparator INDEXORDER;    
  7.   
  8. //Special comparator for sorting hits according to computed relevance (document score).   
  9. public static final ScoreDocComparator RELEVANCE;  
  10.       
  11. //Special comparator for sorting hits according to index order (document number).   
  12. public static final ScoreDocComparator INDEXORDER;      
  13.   


   有3个方法与排序相关,需要我们实现 分别如下:

Java代码  收藏代码
  1.     
  2. /**   
  3.  * Compares two ScoreDoc objects and returns a result indicating their sort order.    
  4.  * @param i First ScoreDoc    
  5.  * @param j Second ScoreDoc   
  6.  * @return -1 if i should come before j;    
  7.  *         1 if i should come after j;   
  8.  *         0 if they are equal   
  9.  */    
  10. public int compare(ScoreDoc i,ScoreDoc j);     
  11.     
  12. /**   
  13.  * 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.    
  14.  * @param i Document   
  15.  * @return Serializable object   
  16.  */    
  17. public Comparable sortValue(ScoreDoc i);     
  18.     
  19. /**   
  20.  * 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.    
  21.  * @return One of the constants in SortField.    
  22.  */    
  23. public int sortType();    
  24.   
  25.                /** 
  26.      * Compares two ScoreDoc objects and returns a result indicating their sort order.  
  27.      * @param i First ScoreDoc  
  28.      * @param j Second ScoreDoc 
  29.      * @return -1 if i should come before j;  
  30.      *         1 if i should come after j; 
  31.      *         0 if they are equal 
  32.      */  
  33.     public int compare(ScoreDoc i,ScoreDoc j);  
  34.   
  35.     /** 
  36.      * 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.  
  37.      * @param i Document 
  38.      * @return Serializable object 
  39.      */  
  40.     public Comparable sortValue(ScoreDoc i);  
  41.   
  42.     /** 
  43.      * 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.  
  44.      * @return One of the constants in SortField.  
  45.      */  
  46.     public int sortType();     


    看个例子吧!

    该例子为Lucene in Action中的一个实现,用来搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储.

Java代码  收藏代码
  1.     
  2. package com.nikee.lucene;     
  3.     
  4. import java.io.IOException;     
  5.     
  6. import org.apache.lucene.index.IndexReader;     
  7. import org.apache.lucene.index.Term;     
  8. import org.apache.lucene.index.TermDocs;     
  9. import org.apache.lucene.index.TermEnum;     
  10. import org.apache.lucene.search.ScoreDoc;     
  11. import org.apache.lucene.search.ScoreDocComparator;     
  12. import org.apache.lucene.search.SortComparatorSource;     
  13. import org.apache.lucene.search.SortField;     
  14.     
  15. //实现了搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储     
  16. //DistanceComparatorSource 实现了SortComparatorSource接口     
  17. public class DistanceComparatorSource implements SortComparatorSource {     
  18.     private static final long serialVersionUID = 1L;     
  19.          
  20.     // x y 用来保存 坐标位置     
  21.     private int x;     
  22.     private int y;     
  23.          
  24.     public DistanceComparatorSource(int x, int y) {     
  25.         this.x = x;     
  26.         this.y = y;     
  27.     }     
  28.          
  29.     // 返回ScoreDocComparator 用来实现排序功能     
  30.     public ScoreDocComparator newComparator(IndexReader reader, String fieldname) throws IOException {     
  31.         return new DistanceScoreDocLookupComparator(reader, fieldname, x, y);     
  32.     }     
  33.          
  34.     //DistanceScoreDocLookupComparator 实现了ScoreDocComparator 用来排序     
  35.     private static class DistanceScoreDocLookupComparator implements ScoreDocComparator {     
  36.         private float[] distances;  // 保存每个餐馆到指定点的距离     
  37.              
  38.         // 构造函数 , 构造函数在这里几乎完成所有的准备工作.     
  39.         public DistanceScoreDocLookupComparator(IndexReader reader, String fieldname, int x, int y) throws IOException {     
  40.             System.out.println("fieldName2="+fieldname);     
  41.             final TermEnum enumerator = reader.terms(new Term(fieldname, ""));     
  42.                  
  43.             System.out.println("maxDoc="+reader.maxDoc());     
  44.             distances = new float[reader.maxDoc()];  // 初始化distances     
  45.             if (distances.length > 0) {     
  46.                 TermDocs termDocs = reader.termDocs();     
  47.                 try {     
  48.                     if (enumerator.term() == null) {     
  49.                         throw new RuntimeException("no terms in field " + fieldname);     
  50.                     }     
  51.                     int i = 0,j = 0;     
  52.                     do {     
  53.                         System.out.println("in do-while :" + i ++);     
  54.                         Term term = enumerator.term();  // 取出每一个Term      
  55.                         if (term.field() != fieldname)  // 与给定的域不符合则比较下一个     
  56.                             break;     
  57.                              
  58.                         //Sets this to the data for the current term in a TermEnum.      
  59.                         //This may be optimized in some implementations.     
  60.                         termDocs.seek(enumerator); //参考TermDocs Doc     
  61.                         while (termDocs.next()) {     
  62.                             System.out.println("    in while :" + j ++);     
  63.                             System.out.println("    in while ,Term :" + term.toString());     
  64.                                  
  65.                             String[] xy = term.text().split(","); // 去处x y     
  66.                             int deltax = Integer.parseInt(xy[0]) - x;     
  67.                             int deltay = Integer.parseInt(xy[1]) - y;     
  68.                             // 计算距离     
  69.                             distances[termDocs.doc()] = (float) Math.sqrt(deltax * deltax + deltay * deltay);     
  70.                         }     
  71.                     }      
  72.                     while (enumerator.next());     
  73.                 } finally {     
  74.                     termDocs.close();     
  75.                 }     
  76.             }     
  77.         }     
  78.     
  79.         //有上面的构造函数的准备 这里就比较简单了     
  80.         public int compare(ScoreDoc i, ScoreDoc j) {     
  81.             if (distances[i.doc] < distances[j.doc])     
  82.                 return -1;     
  83.             if (distances[i.doc] > distances[j.doc])     
  84.                 return 1;     
  85.             return 0;     
  86.         }     
  87.              
  88.         // 返回距离     
  89.         public Comparable sortValue(ScoreDoc i) {     
  90.             return new Float(distances[i.doc]);     
  91.         }     
  92.              
  93.         //指定SortType     
  94.         public int sortType() {     
  95.             return SortField.FLOAT;     
  96.         }     
  97.     }     
  98.              
  99.     public String toString() {     
  100.         return "Distance from (" + x + "," + y + ")";     
  101.     }     
  102. }     

 

Java代码  收藏代码
  1.    
  2. package com.nikee.lucene;  
  3.   
  4. import java.io.IOException;  
  5.   
  6. import org.apache.lucene.index.IndexReader;  
  7. import org.apache.lucene.index.Term;  
  8. import org.apache.lucene.index.TermDocs;  
  9. import org.apache.lucene.index.TermEnum;  
  10. import org.apache.lucene.search.ScoreDoc;  
  11. import org.apache.lucene.search.ScoreDocComparator;  
  12. import org.apache.lucene.search.SortComparatorSource;  
  13. import org.apache.lucene.search.SortField;  
  14.   
  15. //实现了搜索距你最近的餐馆的名字. 餐馆坐标用字符串"x,y"来存储  
  16. //DistanceComparatorSource 实现了SortComparatorSource接口  
  17. public class DistanceComparatorSource implements SortComparatorSource {  
  18.     private static final long serialVersionUID = 1L;  
  19.       
  20.     // x y 用来保存 坐标位置  
  21.     private int x;  
  22.     private int y;  
  23.       
  24.     public DistanceComparatorSource(int x, int y) {  
  25.         this.x = x;  
  26.         this.y = y;  
  27.     }  
  28.       
  29.     // 返回ScoreDocComparator 用来实现排序功能  
  30.     public ScoreDocComparator newComparator(IndexReader reader, String fieldname) throws IOException {  
  31.         return new DistanceScoreDocLookupComparator(reader, fieldname, x, y);  
  32.     }  
  33.       
  34.     //DistanceScoreDocLookupComparator 实现了ScoreDocComparator 用来排序  
  35.     private static class DistanceScoreDocLookupComparator implements ScoreDocComparator {  
  36.         private float[] distances;  // 保存每个餐馆到指定点的距离  
  37.           
  38.         // 构造函数 , 构造函数在这里几乎完成所有的准备工作.  
  39.         public DistanceScoreDocLookupComparator(IndexReader reader, String fieldname, int x, int y) throws IOException {  
  40.             System.out.println("fieldName2="+fieldname);  
  41.             final TermEnum enumerator = reader.terms(new Term(fieldname, ""));  
  42.               
  43.             System.out.println("maxDoc="+reader.maxDoc());  
  44.             distances = new float[reader.maxDoc()];  // 初始化distances  
  45.             if (distances.length > 0) {  
  46.                 TermDocs termDocs = reader.termDocs();  
  47.                 try {  
  48.                     if (enumerator.term() == null) {  
  49.                         throw new RuntimeException("no terms in field " + fieldname);  
  50.                     }  
  51.                     int i = 0,j = 0;  
  52.                     do {  
  53.                         System.out.println("in do-while :" + i ++);  
  54.                         Term term = enumerator.term();  // 取出每一个Term   
  55.                         if (term.field() != fieldname)  // 与给定的域不符合则比较下一个  
  56.                             break;  
  57.                           
  58.                         //Sets this to the data for the current term in a TermEnum.   
  59.                         //This may be optimized in some implementations.  
  60.                         termDocs.seek(enumerator); //参考TermDocs Doc  
  61.                         while (termDocs.next()) {  
  62.                             System.out.println("    in while :" + j ++);  
  63.                             System.out.println("    in while ,Term :" + term.toString());  
  64.                               
  65.                             String[] xy = term.text().split(","); // 去处x y  
  66.                             int deltax = Integer.parseInt(xy[0]) - x;  
  67.                             int deltay = Integer.parseInt(xy[1]) - y;  
  68.                             // 计算距离  
  69.                             distances[termDocs.doc()] = (float) Math.sqrt(deltax * deltax + deltay * deltay);  
  70.                         }  
  71.                     }   
  72.                     while (enumerator.next());  
  73.                 } finally {  
  74.                     termDocs.close();  
  75.                 }  
  76.             }  
  77.         }  
  78.   
  79.         //有上面的构造函数的准备 这里就比较简单了  
  80.         public int compare(ScoreDoc i, ScoreDoc j) {  
  81.             if (distances[i.doc] < distances[j.doc])  
  82.                 return -1;  
  83.             if (distances[i.doc] > distances[j.doc])  
  84.                 return 1;  
  85.             return 0;  
  86.         }  
  87.           
  88.         // 返回距离  
  89.         public Comparable sortValue(ScoreDoc i) {  
  90.             return new Float(distances[i.doc]);  
  91.         }  
  92.           
  93.         //指定SortType  
  94.         public int sortType() {  
  95.             return SortField.FLOAT;  
  96.         }  
  97.     }  
  98.           
  99.     public String toString() {  
  100.         return "Distance from (" + x + "," + y + ")";  
  101.     }  
  102. }  


  这是一个实现了上面两个接口的两个类, 里面带有详细注释, 可以看出 自定义排序并不是很难的. 该实现能否正确实现,我们来看看测试代码能否通过吧.

Java代码  收藏代码
  1.     
  2. package com.nikee.lucene.test;     
  3.     
  4. import java.io.IOException;     
  5.     
  6. import junit.framework.TestCase;     
  7.     
  8. import org.apache.lucene.analysis.WhitespaceAnalyzer;     
  9. import org.apache.lucene.document.Document;     
  10. import org.apache.lucene.document.Field;     
  11. import org.apache.lucene.index.IndexWriter;     
  12. import org.apache.lucene.index.Term;     
  13. import org.apache.lucene.search.FieldDoc;     
  14. import org.apache.lucene.search.Hits;     
  15. import org.apache.lucene.search.IndexSearcher;     
  16. import org.apache.lucene.search.Query;     
  17. import org.apache.lucene.search.ScoreDoc;     
  18. import org.apache.lucene.search.Sort;     
  19. import org.apache.lucene.search.SortField;     
  20. import org.apache.lucene.search.TermQuery;     
  21. import org.apache.lucene.search.TopFieldDocs;     
  22. import org.apache.lucene.store.RAMDirectory;     
  23.     
  24. import com.nikee.lucene.DistanceComparatorSource;     
  25.     
  26. public class DistanceComparatorSourceTest extends TestCase {     
  27.     private RAMDirectory directory;     
  28.          
  29.     private IndexSearcher searcher;     
  30.     private Query query;     
  31.          
  32.     //建立测试环境     
  33.     protected void setUp() throws Exception {     
  34.         directory = new RAMDirectory();     
  35.         IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true);     
  36.              
  37.         addPoint(writer, "El Charro", "restaurant", 1, 2);     
  38.         addPoint(writer, "Cafe Poca Cosa", "restaurant", 5, 9);     
  39.         addPoint(writer, "Los Betos", "restaurant", 9, 6);     
  40.         addPoint(writer, "Nico's Taco Shop", "restaurant", 3, 8);     
  41.     
  42.         writer.close();     
  43.         searcher = new IndexSearcher(directory);     
  44.         query = new TermQuery(new Term("type", "restaurant"));     
  45.     }     
  46.          
  47.     private void addPoint(IndexWriter writer, String name, String type, int x, int y) throws IOException {     
  48.         Document doc = new Document();     
  49.         doc.add(new Field("name", name, Field.Store.YES, Field.Index.TOKENIZED));     
  50.         doc.add(new Field("type", type, Field.Store.YES, Field.Index.TOKENIZED));     
  51.         doc.add(new Field("location", x + "," + y, Field.Store.YES, Field.Index.UN_TOKENIZED));     
  52.         writer.addDocument(doc);     
  53.     }     
  54.          
  55.     public void testNearestRestaurantToHome() throws Exception {     
  56.         //使用DistanceComparatorSource来构造一个SortField     
  57.         Sort sort = new Sort(new SortField("location", new DistanceComparatorSource(0, 0)));     
  58.         Hits hits = searcher.search(query, sort);  // 搜索     
  59.              
  60.         //测试     
  61.         assertEquals("closest", "El Charro", hits.doc(0).get("name"));     
  62.         assertEquals("furthest", "Los Betos", hits.doc(3).get("name"));     
  63.     }     
  64.          
  65.     public void testNeareastRestaurantToWork() throws Exception {     
  66.         Sort sort = new Sort(new SortField("location", new DistanceComparatorSource(10, 10)));  // 工作的坐标 10,10     
  67.         //上面的测试实现了自定义排序,但是并不能访问自定义排序的更详细信息,利用     
  68.         //TopFieldDocs 可以进一步访问相关信息     
  69.         TopFieldDocs docs = searcher.search(query, null, 3, sort);     
  70.              
  71.         assertEquals(4, docs.totalHits);     
  72.         assertEquals(3, docs.scoreDocs.length);     
  73.              
  74.         //取得FieldDoc 利用FieldDoc可以取得关于排序的更详细信息 请查看FieldDoc Doc     
  75.         FieldDoc fieldDoc = (FieldDoc) docs.scoreDocs[0];     
  76.     
  77.         assertEquals("(10,10) -> (9,6) = sqrt(17)", new Float(Math.sqrt(17)), fieldDoc.fields[0]);     
  78.         Document document = searcher.doc(fieldDoc.doc);     
  79.         assertEquals("Los Betos", document.get("name"));     
  80.         dumpDocs(sort, docs);  // 显示相关信息     
  81.     }     
  82.          
  83.     // 显示有关排序的信息     
  84.     private void dumpDocs(Sort sort, TopFieldDocs docs) throws IOException {     
  85.         System.out.println("Sorted by: " + sort);     
  86.         ScoreDoc[] scoreDocs = docs.scoreDocs;     
  87.         for (int i = 0; i < scoreDocs.length; i++) {     
  88.             FieldDoc fieldDoc = (FieldDoc) scoreDocs[i];     
  89.             Float distance = (Float) fieldDoc.fields[0];     
  90.             Document doc = searcher.doc(fieldDoc.doc);     
  91.             System.out.println("   " + doc.get("name") + " @ (" + doc.get("location") + ") -> " + distance);     
  92.         }     
  93.     }     
  94. }     
Java代码  收藏代码
    1.     
    2. package com.nikee.lucene.test;  
    3.   
    4. import java.io.IOException;  
    5.   
    6. import junit.framework.TestCase;  
    7.   
    8. import org.apache.lucene.analysis.WhitespaceAnalyzer;  
    9. import org.apache.lucene.document.Document;  
    10. import org.apache.lucene.document.Field;  
    11. import org.apache.lucene.index.IndexWriter;  
    12. import org.apache.lucene.index.Term;  
    13. import org.apache.lucene.search.FieldDoc;  
    14. import org.apache.lucene.search.Hits;  
    15. import org.apache.lucene.search.IndexSearcher;  
    16. import org.apache.lucene.search.Query;  
    17. import org.apache.lucene.search.ScoreDoc;  
    18. import org.apache.lucene.search.Sort;  
    19. import org.apache.lucene.search.SortField;  
    20. import org.apache.lucene.search.TermQuery;  
    21. import org.apache.lucene.search.TopFieldDocs;  
    22. import org.apache.lucene.store.RAMDirectory;  
    23.   
    24. import com.nikee.lucene.DistanceComparatorSource;  
    25.   
    26. public class DistanceComparatorSourceTest extends TestCase {  
    27.     private RAMDirectory directory;  
    28.       
    29.     private IndexSearcher searcher;  
    30.     private Query query;  
    31.       
    32.     //建立测试环境  
    33.     protected void setUp() throws Exception {  
    34.         directory = new RAMDirectory();  
    35.         IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true);  
    36.           
    37.         addPoint(writer, "El Charro", "restaurant", 1, 2);  
    38.         addPoint(writer, "Cafe Poca Cosa", "restaurant", 5, 9);  
    39.         addPoint(writer, "Los Betos", "restaurant", 9, 6);  
    40.         addPoint(writer, "Nico's Taco Shop", "restaurant", 3, 8);  
    41.   
    42.         writer.close();  
    43.         searcher = new IndexSearcher(directory);  
    44.         query = new TermQuery(new Term("type", "restaurant"));  
    45.     }  
    46.       
    47.     private void addPoint(IndexWriter writer, String name, String type, int x, int y) throws IOException {  
    48.         Document doc = new Document();  
    49.         doc.add(new Field("name", name, Field.Store.YES, Field.Index.TOKENIZED));  
    50.         doc.add(new Field("type", type, Field.Store.YES, Field.Index.TOKENIZED));  
    51.         doc.add(new Field("location", x + "," + y, Field.Store.YES, Field.Index.UN_TOKENIZED));  
    52.         writer.addDocument(doc);  
    53.     }  
    54.       
    55.     public void testNearestRestaurantToHome() throws Exception {  
    56.         //使用DistanceComparatorSource来构造一个SortField  
    57.         Sort sort = new Sort(new SortField("location", new DistanceComparatorSource(0, 0)));  
    58.         Hits hits = searcher.search(query, sort);  // 搜索  
    59.           
    60.         //测试  
    61.         assertEquals("closest", "El Charro", hits.doc(0).get("name"));  
    62.         assertEquals("furthest", "Los Betos", hits.doc(3).get("name"));  
    63.     }  
    64.       
    65.     public void testNeareastRestaurantToWork() throws Exception {  
    66.         Sort sort = new Sort(new SortField("location", new DistanceComparatorSource(10, 10)));  // 工作的坐标 10,10  
    67.         //上面的测试实现了自定义排序,但是并不能访问自定义排序的更详细信息,利用  
    68.         //TopFieldDocs 可以进一步访问相关信息  
    69.         TopFieldDocs docs = searcher.search(query, null, 3, sort);  
    70.           
    71.         assertEquals(4, docs.totalHits);  
    72.         assertEquals(3, docs.scoreDocs.length);  
    73.           
    74.         //取得FieldDoc 利用FieldDoc可以取得关于排序的更详细信息 请查看FieldDoc Doc  
    75.         FieldDoc fieldDoc = (FieldDoc) docs.scoreDocs[0];  
    76.   
    77.         assertEquals("(10,10) -> (9,6) = sqrt(17)", new Float(Math.sqrt(17)), fieldDoc.fields[0]);  
    78.         Document document = searcher.doc(fieldDoc.doc);  
    79.         assertEquals("Los Betos", document.get("name"));  
    80.         dumpDocs(sort, docs);  // 显示相关信息  
    81.     }  
    82.       
    83.     // 显示有关排序的信息  
    84.     private void dumpDocs(Sort sort, TopFieldDocs docs) throws IOException {  
    85.         System.out.println("Sorted by: " + sort);  
    86.         ScoreDoc[] scoreDocs = docs.scoreDocs;  
    87.         for (int i = 0; i < scoreDocs.length; i++) {  
    88.             FieldDoc fieldDoc = (FieldDoc) scoreDocs[i];  
    89.             Float distance = (Float) fieldDoc.fields[0];  
    90.             Document doc = searcher.doc(fieldDoc.doc);  
    91.             System.out.println("   " + doc.get("name") + " @ (" + doc.get("location") + ") -> " + distance);  
    92.         }  
    93.     }  
    94. }   

转载 http://zhxmyself.iteye.com/blog/478638

posted on 2014-06-29 02:34  刺猬的温驯  阅读(1603)  评论(0编辑  收藏  举报