分享

一步一步学lucene——(第四步:搜索篇)

本帖最后由 pig2 于 2015-4-20 00:35 编辑
问题导读:
1、lucene搜索分页有哪两种方式?
2、不做缓存如何查询数据?
3、lucene的主要API有哪些?




接上篇: 一步一步学lucene——(第三步:索引篇)
下面说的主要是lucene如何进行搜索,相比于建索引,搜索可能更能提起大家的兴趣。
lucene的主要搜索的API下面通过表格来看一下lucene用到的主要的搜索API
目的
IndexSeacher搜索操作的入口,所有搜索操作都是通过IndexSeacher实例使用一个重载的search方法来实现
Query(及其子类)具体的Query子类为每一种特定类型的查询进行逻辑上的封装。Query实例被传递到IndexSearcher的search方法中
QueryParser将用户输入的(并且可读的)查询表达式处理为一个具体的Query对象
TopDocs保持由IndexSearcher.search()方法返回的具有较高评分的顶部文档
ScoreDoc 提供对TopDocs中每条搜索结果的访问接口

对特定项进行搜索其中IndexSearcher是对索引中文档进行搜索的核心类,我们下面的例子中就会对subject域进行索引,使用的是Query的子类TermQuery。
测试程序如下:
  1. public void testTerm() throws Exception {
  2.     Directory dir = TestUtil.getBookIndexDirectory(); //A
  3.     IndexSearcher searcher = new IndexSearcher(dir);  //B
  4.     Term t = new Term("subject", "ant");
  5.     Query query = new TermQuery(t);
  6.     TopDocs docs = searcher.search(query, 10);
  7.     assertEquals("Ant in Action",                //C
  8.                  1, docs.totalHits);                         //C
  9.     t = new Term("subject", "junit");
  10.     docs = searcher.search(new TermQuery(t), 10);
  11.     assertEquals("Ant in Action, " +                                 //D
  12.                  "JUnit in Action, Second Edition",                  //D
  13.                  2, docs.totalHits);                                 //D
  14.     searcher.close();
  15.     dir.close();
  16.   }
复制代码


当然在不同的情况下你可以改变其中的代码来搜索你想要的东西。
解析用户查询lucene中解析用户的查询需要一个Query对象作为参数。那么也就是将Expression组合成Query的过程,这里边有一个对象叫QueryParser,它将前面传过来的规则的解析成对象然后进行查询。下面我们看下流程是如何处理的:
index.png
            图:QueryParser对象处理复杂的表达式的过程
下面看一个程序示例,这个是基于lucene 3.0的,在后面的版本中会有所变化。
程序结构如下:
  1. public void testQueryParser() throws Exception {
  2.     Directory dir = TestUtil.getBookIndexDirectory();
  3.     IndexSearcher searcher = new IndexSearcher(dir);
  4.     QueryParser parser = new QueryParser(Version.LUCENE_30,      //A
  5.                                          "contents",                  //A
  6.                                          new SimpleAnalyzer());       //A
  7.     Query query = parser.parse("+JUNIT +ANT -MOCK");                  //B
  8.     TopDocs docs = searcher.search(query, 10);
  9.     assertEquals(1, docs.totalHits);
  10.     Document d = searcher.doc(docs.scoreDocs[0].doc);
  11.     assertEquals("Ant in Action", d.get("title"));
  12.     query = parser.parse("mock OR junit");                            //B
  13.     docs = searcher.search(query, 10);
  14.     assertEquals("Ant in Action, " +
  15.                  "JUnit in Action, Second Edition",
  16.                  2, docs.totalHits);
  17.     searcher.close();
  18.     dir.close();
  19.   }
复制代码


其实主要就是A和B两部分,将规则解析成lucene能识别的表达式。
下面的表格中列出了查询表达式的范例:
表达式匹配文档
java在字段中包含java
java junit
java or junit
在字段中包含java或者junit
+java +junit
java and junit
在字段中包含java以及junit
title:ant在title字段中包含ant
title:extreme
-subject:sports
title:extreme
AND NOT subject:sports
在title字段中包含extreme并且在subject字段中不能包含sports
(agile OR extreme) AND methodology在字段中包含methodology并且同时包括agile或者extreme
title:"junit in action"在title字段中包含junit in action
title:"junit action"~5包含5次junit和action
java*包含以java开头的,例如:javaspaces,javaserver
java~包含和java相似的,如lava
lastmodified:[1/1/04 TO 12/31/04]在lastmodified字段中值为2004-01-01到2004-12-31中间的
接下来测试一下QueryParser的各个表达式,程序结构如下:
  1. public class TestQueryParser {
  2.     public static void main(String[] args) throws Exception {
  3.         String[] id = { "1", "2", "3" };
  4.         String[] contents = { "java and lucene is good",
  5.                 "I had study java and jbpm",
  6.                 "I want to study java,hadoop and hbase" };
  7.         Directory directory = new RAMDirectory();
  8.         IndexWriter indexWriter = new IndexWriter(directory,
  9.                 new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(
  10.                         Version.LUCENE_36)));
  11.         for (int i = 0; i < id.length; i++) {
  12.             Document document = new Document();
  13.             document.add(new Field("id", id[i], Field.Store.YES,
  14.                     Field.Index.ANALYZED));
  15.             document.add(new Field("contents", contents[i], Field.Store.YES,
  16.                     Field.Index.ANALYZED));
  17.             indexWriter.addDocument(document);
  18.         }
  19.         indexWriter.close();
  20.         System.out.println("String is :java");
  21.         search(directory, "java");
  22.         System.out.println("\nString is :lucene");
  23.         search(directory, "lucene");
  24.         System.out.println("\nString is :+java +jbpm");
  25.         search(directory, "+java +jbpm");
  26.         System.out.println("\nString is :+java -jbpm");
  27.         search(directory, "+java -jbpm");
  28.         System.out.println("\nString is :java jbpm");
  29.         search(directory, "java jbpm");
  30.         System.out.println("\nString is :java AND jbpm");
  31.         search(directory, "java AND jbpm");
  32.         System.out.println("\nString is :java or jbpm");
  33.         search(directory, "java or jbpm");
  34.     }
  35.     public static void search(Directory directory, String str) throws Exception {
  36.         IndexSearcher indexSearcher = new IndexSearcher(directory);
  37.         Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_34);
  38.         QueryParser queryParser = new QueryParser(Version.LUCENE_34,
  39.                 "contents", analyzer);
  40.         Query query = queryParser.parse(str);
  41.         TopDocs topDocs = indexSearcher.search(query, 10);
  42.         ScoreDoc[] scoreDoc = topDocs.scoreDocs;
  43.         for (int i = 0; i < scoreDoc.length; i++) {
  44.             Document doc = indexSearcher.doc(scoreDoc[i].doc);
  45.             System.out.println(doc.get("id") + " " + doc.get("contents"));
  46.         }
  47.         indexSearcher.close();
  48.     }
  49. }
复制代码


运行程序就会得到输出结果。
搜索用到的各个类的相互关系我想看图应该会比较清晰,下面的图比较清晰的组合了程序的结构:
index.png
      图:搜索用到的各个类的相互关系
搜索结果分页其实这个所谓的分页跟数据库的分页功能差不多,只是一个是从数据库中读取数据,而一个是从索引文件中找到对应的数据。
在lucene搜索分页过程中,可以有两种方式:
  • 一种是将搜索结果集直接放到session中,但是假如结果集非常大,同时又存在大并发访问的时候,很可能造成服务器的内存不足,而使服务器宕机
  • 还有一种是每次都重新进行搜索,这样虽然避免了内存溢出的可能,但是,每次搜索都要进行一次IO操作,如果大并发访问的时候,你要保证你的硬盘的转速足够的快,还要保证你的cpu有足够高的频率
而我们可以将这两种方式结合下,每次查询都多缓存一部分的结果集,翻页的时候看看所查询的内容是不是在已经存在在缓存当中,如果已经存在了就直接拿出来,如果不存在,就进行查询后,从缓存中读出来。
比如:现在我们有一个搜索结果集 一个有100条数据,每页显示10条,就有10页数据。按照第一种的思路就是,我直接把这100条数据缓存起来,每次翻页时从缓存种读取而第二种思路就是,我直接从搜索到的结果集种显示前十条给第一页显示,第二页的时候,我在查询一次,给出10-20条数据给第二页显示,我每次翻页都要重新查询。
第三种思路就变成了
我第一页仅需要10条数据,但是我一次读出来50条数据,把这50条数据放入到缓存当中,当我需要10--20之 间的数据的时候,我的发现我的这些数据已经在我的缓存种存在了,我就直接存缓存中把数据读出来,少了一次查询,速度自然也提高了很多. 如果我访问第六页的数据,我就把我的缓存更新一次.这样连续翻页10次才进行两次IO操作同时又保证了内存不容易被溢出.而具体缓存设置多少,要看你的服务器的能力和访问的人数来决定。
下面是一个示例程序没有做缓存,缓存的部分可以自己实现,也可以选择ehcache等开源的实现。
程序结构如下:
  1. public class TestPagation {
  2.     public void paginationQuery(String keyWord, int pageSize, int currentPage)
  3.             throws ParseException, CorruptIndexException, IOException {
  4.         String[] fields = { "title", "content" };
  5.         // 创建一个分词器,和创建索引时用的分词器要一致
  6.         Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
  7.         
  8.         QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_36,
  9.                 fields, analyzer);
  10.         Query query = queryParser.parse(keyWord);
  11.         
  12.         // 打开索引目录
  13.         File indexDir = new File("./indexDir");
  14.         Directory directory = FSDirectory.open(indexDir);
  15.         IndexReader indexReader = IndexReader.open(directory);
  16.         IndexSearcher indexSearcher = new IndexSearcher(indexReader);
  17.         // TopDocs 搜索返回的结果
  18.         TopDocs topDocs = indexSearcher.search(query, 100);// 只返回前100条记录
  19.         int totalCount = topDocs.totalHits; // 搜索结果总数量
  20.         ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 搜索返回的结果集合
  21.         // 查询起始记录位置
  22.         int begin = pageSize * (currentPage - 1);
  23.         // 查询终止记录位置
  24.         int end = Math.min(begin + pageSize, scoreDocs.length);
  25.         // 进行分页查询
  26.         for (int i = begin; i < end; i++) {
  27.             int docID = scoreDocs[i].doc;
  28.             Document doc = indexSearcher.doc(docID);
  29.             int id = NumericUtils.prefixCodedToInt(doc.get("id"));
  30.             String title = doc.get("title");
  31.             System.out.println("id is : " + id);
  32.             System.out.println("title is : " + title);
  33.         }
  34.     }
  35.    
  36.     public static void main(String[] args) throws CorruptIndexException, ParseException, IOException {
  37.         TestPagation t = new TestPagation();
  38.          //每页显示5条记录,显示第三页的记录
  39.         t.paginationQuery("RUNNING",5,3);
  40.     }
  41. }
复制代码



[源码下载]


资料来源:http://www.cnblogs.com/skyme/archive/2012/08/02/2618341.html



欢迎加入about云群371358502、39327136,云计算爱好者群,亦可关注about云腾讯认证空间||关注本站微信

没找到任何评论,期待你打破沉寂

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条