lucene的多种搜索2-SpanQuery

SpanQuery按照词在文章中的距离或者查询几个相邻词的查询

 

SpanQuery包括以下几种:

SpanTermQuery:词距查询的基础,结果和TermQuery相似,只不过是增加了查询结果中单词的距离信息。

SpanFirstQuery:在指定距离可以找到第一个单词的查询。

SpanNearQuery:查询的几个语句之间保持者一定的距离。

SpanOrQuery:同时查询几个词句查询。

SpanNotQuery:从一个词距查询结果中,去除一个词距查询。

下面一个简单例子介绍

Java代码 复制代码
  1. package com;   
  2.   
  3. //SpanQuery:跨度查询。此类为抽象类。   
  4.   
  5. import java.io.IOException;   
  6. import java.io.StringReader;   
  7. import java.util.ArrayList;   
  8. import java.util.List;   
  9. import org.apache.lucene.analysis.Analyzer;   
  10. import org.apache.lucene.analysis.Token;   
  11. import org.apache.lucene.analysis.TokenStream;   
  12. import org.apache.lucene.analysis.WhitespaceAnalyzer;   
  13. import org.apache.lucene.document.Document;   
  14. import org.apache.lucene.document.Field;   
  15. import org.apache.lucene.document.Field.Index;   
  16. import org.apache.lucene.document.Field.Store;   
  17. import org.apache.lucene.index.IndexReader;   
  18. import org.apache.lucene.index.IndexWriter;   
  19. import org.apache.lucene.index.Term;   
  20. import org.apache.lucene.search.Hits;   
  21. import org.apache.lucene.search.IndexSearcher;   
  22. import org.apache.lucene.search.spans.SpanFirstQuery;   
  23. import org.apache.lucene.search.spans.SpanNearQuery;   
  24. import org.apache.lucene.search.spans.SpanNotQuery;   
  25. import org.apache.lucene.search.spans.SpanOrQuery;   
  26. import org.apache.lucene.search.spans.SpanQuery;   
  27. import org.apache.lucene.search.spans.SpanTermQuery;   
  28. import org.apache.lucene.search.spans.Spans;   
  29. import org.apache.lucene.store.RAMDirectory;   
  30.   
  31. public class SpanQueryTest {   
  32.   
  33.     private RAMDirectory directory;   
  34.   
  35.     private IndexSearcher indexSearcher;   
  36.   
  37.     private IndexReader reader;   
  38.   
  39.     private SpanTermQuery quick;   
  40.   
  41.     private SpanTermQuery brown;   
  42.   
  43.     private SpanTermQuery red;   
  44.   
  45.     private SpanTermQuery fox;   
  46.   
  47.     private SpanTermQuery lazy;   
  48.   
  49.     private SpanTermQuery sleepy;   
  50.   
  51.     private SpanTermQuery dog;   
  52.   
  53.     private SpanTermQuery cat;   
  54.   
  55.     private Analyzer analyzer;   
  56.        
  57.     // 索引及初使化   
  58.     public void index() throws IOException {   
  59.   
  60.         directory = new RAMDirectory();   
  61.   
  62.         analyzer = new WhitespaceAnalyzer();   
  63.   
  64.         IndexWriter writer = new IndexWriter(directory, analyzer, true);   
  65.   
  66.         Document doc1 = new Document();   
  67.   
  68.         doc1.add(new Field("field",   
  69.                 "the quick brown fox jumps over the lazy dog", Store.YES,   
  70.                 Index.TOKENIZED));   
  71.   
  72.         Document doc2 = new Document();   
  73.   
  74.         doc2.add(new Field("field",   
  75.                 "the quick red fox jumps over the sleepy cat", Store.YES,   
  76.                 Index.TOKENIZED));   
  77.   
  78.         writer.addDocument(doc1);   
  79.   
  80.         writer.addDocument(doc2);   
  81.   
  82.         writer.optimize();   
  83.   
  84.         writer.close();   
  85.   
  86.         quick = new SpanTermQuery(new Term("field", "quick"));   
  87.   
  88.         brown = new SpanTermQuery(new Term("field", "brown"));   
  89.   
  90.         red = new SpanTermQuery(new Term("field", "red"));   
  91.   
  92.         fox = new SpanTermQuery(new Term("field", "fox"));   
  93.         lazy = new SpanTermQuery(new Term("field", "lazy"));   
  94.         sleepy = new SpanTermQuery(new Term("field", "sleepy"));   
  95.         dog = new SpanTermQuery(new Term("field", "dog"));   
  96.         cat = new SpanTermQuery(new Term("field", "cat"));   
  97.   
  98.         indexSearcher = new IndexSearcher(directory);   
  99.   
  100.         reader = IndexReader.open(directory);   
  101.     }   
  102.   
  103.     private void dumpSpans(SpanQuery query) throws IOException {   
  104.   
  105.         // 检索效果和TermQuery一样,可以把他当成TermQuery   
  106.         Hits hits = indexSearcher.search(query);   
  107.         for (int i = 0; i < hits.length(); i++) {   
  108.             // System.out.println(hits.doc(i).get("field"));   
  109.         }   
  110.   
  111.         // 但内部会记录一些位置信息,供SpanQuery的其它API使用,是其它属于SpanQuery的Query的基础。   
  112.   
  113.         Spans spans = query.getSpans(reader);   
  114.   
  115.         int numSpans = 0;   
  116.   
  117.         float[] scores = new float[2];   
  118.         for (int i = 0; i < hits.length(); i++) {   
  119.             scores[hits.id(i)] = hits.score(i);   
  120.         }   
  121.   
  122.         while (spans.next()) {   
  123.   
  124.             numSpans++;   
  125.   
  126.             int id = spans.doc();   
  127.   
  128.             Document doc = reader.document(id);   
  129.   
  130.             Token[] tokens = AnalyzerUtils.tokensFromAnalysis(analyzer, doc   
  131.                     .get("field"));   
  132.   
  133.             StringBuffer buffer = new StringBuffer();   
  134.   
  135.             for (int i = 0; i < tokens.length; i++) {   
  136.                 // the quick brown fox jumps over the lazy dog   
  137.                 // spans记录了位置信息,比如搜索brown,brown在这句话中位于第三个位置,所以spans.start()=2,spans.end()=3   
  138.                 // 在第二项的位置后加<,第三项后加> 返回<brown>   
  139.                 if (i == spans.start()) {   
  140.                     buffer.append("<");   
  141.                 }   
  142.                 buffer.append(tokens[i].termText());   
  143.                 if (i + 1 == spans.end()) {   
  144.                     buffer.append(">");   
  145.                 }   
  146.                 buffer.append(" ");   
  147.             }   
  148.             buffer.append("(" + scores[id] + ") ");   
  149.   
  150.             System.out.println(buffer);   
  151.         }   
  152.   
  153.         // indexSearcher.close();   
  154.     }   
  155.   
  156.     // SpanTermQuery:检索效果完全同TermQuery,但内部会记录一些位置信息,供SpanQuery的其它API使用,是其它属于SpanQuery的Query的基础。   
  157.     public void spanTermQueryTest() throws IOException {   
  158.         dumpSpans(brown);   
  159.            
  160.         //// 搜索结果   
  161.         // the quick <brown> fox jumps over the lazy dog (0.22097087)    
  162.     }   
  163.   
  164.     // SpanFirstQuery:查找方式为从Field的内容起始位置开始,在一个固定的宽度内查找所指定的词条。   
  165.     public void spanFirstQueryTest() throws IOException {   
  166.         // the quick brown fox jumps over the lazy dog   
  167.         // 在给定的范围搜索,前两个为the quick   
  168.         // brown 在doc1的第三个位置,用SpanFirstQuery从起点查找的话,他的跨度必须为>=3才能找到   
  169.         SpanFirstQuery firstQuery = new SpanFirstQuery(brown, 3);   
  170.         dumpSpans(firstQuery);   
  171.            
  172.         ////搜索结果   
  173.         // the quick <brown> fox jumps over the lazy dog (0.22097087)    
  174.     }   
  175.   
  176.     // SpanNearQuery:功能类似PharaseQuery。SpanNearQuery查找所匹配的不一定是短语,还有可能是另一个SpanQuery的查询结果作为整体考虑,进行嵌套查询。   
  177.     public void spanNearQueryTest() throws IOException {   
  178.         // the quick brown fox jumps over the lazy dog   
  179.   
  180.         // 第二个参数为两个项的位置之间允许的最大间隔   
  181.         // 在这里两个较远的项为quick和fox,他们之是的最大间隔为5,所以slop必须>=5才能搜到结果   
  182.         SpanNearQuery nearQuery = new SpanNearQuery(new SpanQuery[] { quick,   
  183.                 brown, fox }, 5true);   
  184.   
  185.         dumpSpans(nearQuery);   
  186.   
  187.         // 与PhraseQuery短语搜索相似   
  188.         // 这里搜索quick,dog,brown,要想得到结果,就要将brown向后移动5个位置才能到dog的后面,所以slop要>=5才能找到结果   
  189.         // 第三个参数,如果为true表示保持各项位置不变,顺序搜索   
  190.         nearQuery = new SpanNearQuery(new SpanQuery[] { quick, dog, brown }, 5,   
  191.                 false);   
  192.   
  193.         dumpSpans(nearQuery);   
  194.            
  195.         //////搜索结果/////   
  196.         // 第一个dumpSpans的结果 the <quick brown fox> jumps over the lazy dog (0.34204215)    
  197.         // 第二个dumpSpans的结果 the <quick brown fox jumps over the lazy dog> (0.27026406)    
  198.     }   
  199.   
  200.     // 从第一个SpanQuery查询结果中,去掉第二个SpanQuery查询结果,作为检索结果   
  201.     public void spanNotQueryTest() throws IOException {   
  202.            
  203.         // the quick brown fox jumps over the lazy dog   
  204.   
  205.         SpanNearQuery quick_fox = new SpanNearQuery(new SpanQuery[] { quick,   
  206.                 fox }, 1true);   
  207.   
  208.         // 结果为quick brown fox 和 quick red fox   
  209.         dumpSpans(quick_fox);   
  210.   
  211.         // SpanNotQuery quick_fox_dog = new SpanNotQuery(quick_fox, dog);   
  212.         //   
  213.         // dumpSpans(quick_fox_dog);   
  214.   
  215.         // 在quick_fox结果中,去掉red,结果为quick brown fox   
  216.         SpanNotQuery no_quick_red_fox = new SpanNotQuery(quick_fox, red);   
  217.   
  218.         dumpSpans(no_quick_red_fox);   
  219.            
  220.         //////搜索结果///////第一个dumpSpans结果为前两条,第二个dumpSpans结果为第三条   
  221.         //the <quick brown fox> jumps over the lazy dog (0.18579213)    
  222.         //the <quick red fox> jumps over the sleepy cat (0.18579213)    
  223.         //the <quick brown fox> jumps over the lazy dog (0.18579213)    
  224.     }   
  225.   
  226.     // SpanOrQuery:把所有SpanQuery查询结果综合起来,作为检索结果。   
  227.     public void spanOrQueryTest() throws IOException   {   
  228.            
  229.         SpanNearQuery quick_fox = new SpanNearQuery(new SpanQuery[] { quick,   
  230.                 fox }, 1true);   
  231.            
  232.         SpanNearQuery lazy_dog = new SpanNearQuery(   
  233.                 new SpanQuery[] { lazy, dog }, 0true);   
  234.   
  235.         SpanNearQuery sleepy_cat = new SpanNearQuery(new SpanQuery[] { sleepy,   
  236.                 cat }, 0true);   
  237.   
  238.         SpanNearQuery qf_near_ld = new SpanNearQuery(new SpanQuery[] {   
  239.                 quick_fox, lazy_dog }, 3true);   
  240.            
  241.         dumpSpans(qf_near_ld);   
  242.   
  243.         SpanNearQuery qf_near_sc = new SpanNearQuery(new SpanQuery[] {   
  244.                 quick_fox, sleepy_cat }, 3true);   
  245.            
  246.         dumpSpans(qf_near_sc);   
  247.   
  248.         SpanOrQuery or = new SpanOrQuery(new SpanQuery[] { qf_near_ld,   
  249.                 qf_near_sc });   
  250.            
  251.         dumpSpans(or);   
  252.            
  253.         /////////搜索结果 第一个dumpSpans结果为第一条,第二个为第二条,第三个为第三,四条   
  254.         // the <quick brown fox jumps over the lazy dog> (0.3321948)    
  255.         // the <quick red fox jumps over the sleepy cat> (0.3321948)    
  256.         // the <quick brown fox jumps over the lazy dog> (0.5405281)    
  257.         // the <quick red fox jumps over the sleepy cat> (0.5405281)    
  258.     }   
  259.   
  260.     public static void main(String[] args) throws IOException {   
  261.   
  262.         SpanQueryTest test = new SpanQueryTest();   
  263.   
  264.         test.index();   
  265.   
  266.         test.spanOrQueryTest();   
  267.     }   
  268. }   
  269.   
  270. class AnalyzerUtils {   
  271.     public static Token[] tokensFromAnalysis(Analyzer analyzer, String text)   
  272.             throws IOException {   
  273.         TokenStream stream = analyzer.tokenStream("contents", new StringReader(   
  274.                 text));   
  275.         boolean b = true;   
  276.         List<Token> list = new ArrayList<Token>();   
  277.         while (b) {   
  278.             Token token = stream.next();   
  279.             if (token == null)   
  280.                 b = false;   
  281.             else  
  282.                 list.add(token);   
  283.         }   
  284.         return (Token[]) list.toArray(new Token[0]);   
  285.     }   
  286. }  

posted on 2015-12-08 21:43  1130136248  阅读(239)  评论(0编辑  收藏  举报

导航