本帖最后由 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。
测试程序如下:
- public void testTerm() throws Exception {
- Directory dir = TestUtil.getBookIndexDirectory(); //A
- IndexSearcher searcher = new IndexSearcher(dir); //B
-
- Term t = new Term("subject", "ant");
- Query query = new TermQuery(t);
- TopDocs docs = searcher.search(query, 10);
- assertEquals("Ant in Action", //C
- 1, docs.totalHits); //C
-
- t = new Term("subject", "junit");
- docs = searcher.search(new TermQuery(t), 10);
- assertEquals("Ant in Action, " + //D
- "JUnit in Action, Second Edition", //D
- 2, docs.totalHits); //D
-
- searcher.close();
- dir.close();
- }
复制代码
当然在不同的情况下你可以改变其中的代码来搜索你想要的东西。
解析用户查询lucene中解析用户的查询需要一个Query对象作为参数。那么也就是将Expression组合成Query的过程,这里边有一个对象叫QueryParser,它将前面传过来的规则的解析成对象然后进行查询。下面我们看下流程是如何处理的:
图:QueryParser对象处理复杂的表达式的过程
下面看一个程序示例,这个是基于lucene 3.0的,在后面的版本中会有所变化。
程序结构如下:
- public void testQueryParser() throws Exception {
- Directory dir = TestUtil.getBookIndexDirectory();
- IndexSearcher searcher = new IndexSearcher(dir);
-
- QueryParser parser = new QueryParser(Version.LUCENE_30, //A
- "contents", //A
- new SimpleAnalyzer()); //A
-
- Query query = parser.parse("+JUNIT +ANT -MOCK"); //B
- TopDocs docs = searcher.search(query, 10);
- assertEquals(1, docs.totalHits);
- Document d = searcher.doc(docs.scoreDocs[0].doc);
- assertEquals("Ant in Action", d.get("title"));
-
- query = parser.parse("mock OR junit"); //B
- docs = searcher.search(query, 10);
- assertEquals("Ant in Action, " +
- "JUnit in Action, Second Edition",
- 2, docs.totalHits);
-
- searcher.close();
- dir.close();
- }
复制代码
其实主要就是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的各个表达式,程序结构如下:
- public class TestQueryParser {
-
- public static void main(String[] args) throws Exception {
-
- String[] id = { "1", "2", "3" };
- String[] contents = { "java and lucene is good",
- "I had study java and jbpm",
- "I want to study java,hadoop and hbase" };
-
- Directory directory = new RAMDirectory();
- IndexWriter indexWriter = new IndexWriter(directory,
- new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(
- Version.LUCENE_36)));
- for (int i = 0; i < id.length; i++) {
- Document document = new Document();
- document.add(new Field("id", id[i], Field.Store.YES,
- Field.Index.ANALYZED));
- document.add(new Field("contents", contents[i], Field.Store.YES,
- Field.Index.ANALYZED));
- indexWriter.addDocument(document);
- }
- indexWriter.close();
-
- System.out.println("String is :java");
- search(directory, "java");
-
- System.out.println("\nString is :lucene");
- search(directory, "lucene");
-
- System.out.println("\nString is :+java +jbpm");
- search(directory, "+java +jbpm");
-
- System.out.println("\nString is :+java -jbpm");
- search(directory, "+java -jbpm");
-
- System.out.println("\nString is :java jbpm");
- search(directory, "java jbpm");
-
- System.out.println("\nString is :java AND jbpm");
- search(directory, "java AND jbpm");
-
- System.out.println("\nString is :java or jbpm");
- search(directory, "java or jbpm");
- }
-
- public static void search(Directory directory, String str) throws Exception {
- IndexSearcher indexSearcher = new IndexSearcher(directory);
- Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_34);
- QueryParser queryParser = new QueryParser(Version.LUCENE_34,
- "contents", analyzer);
- Query query = queryParser.parse(str);
- TopDocs topDocs = indexSearcher.search(query, 10);
- ScoreDoc[] scoreDoc = topDocs.scoreDocs;
- for (int i = 0; i < scoreDoc.length; i++) {
- Document doc = indexSearcher.doc(scoreDoc[i].doc);
- System.out.println(doc.get("id") + " " + doc.get("contents"));
- }
- indexSearcher.close();
- }
- }
复制代码
运行程序就会得到输出结果。
搜索用到的各个类的相互关系我想看图应该会比较清晰,下面的图比较清晰的组合了程序的结构:
图:搜索用到的各个类的相互关系
搜索结果分页其实这个所谓的分页跟数据库的分页功能差不多,只是一个是从数据库中读取数据,而一个是从索引文件中找到对应的数据。
在lucene搜索分页过程中,可以有两种方式:
- 一种是将搜索结果集直接放到session中,但是假如结果集非常大,同时又存在大并发访问的时候,很可能造成服务器的内存不足,而使服务器宕机
- 还有一种是每次都重新进行搜索,这样虽然避免了内存溢出的可能,但是,每次搜索都要进行一次IO操作,如果大并发访问的时候,你要保证你的硬盘的转速足够的快,还要保证你的cpu有足够高的频率
而我们可以将这两种方式结合下,每次查询都多缓存一部分的结果集,翻页的时候看看所查询的内容是不是在已经存在在缓存当中,如果已经存在了就直接拿出来,如果不存在,就进行查询后,从缓存中读出来。
比如:现在我们有一个搜索结果集 一个有100条数据,每页显示10条,就有10页数据。按照第一种的思路就是,我直接把这100条数据缓存起来,每次翻页时从缓存种读取而第二种思路就是,我直接从搜索到的结果集种显示前十条给第一页显示,第二页的时候,我在查询一次,给出10-20条数据给第二页显示,我每次翻页都要重新查询。
第三种思路就变成了
我第一页仅需要10条数据,但是我一次读出来50条数据,把这50条数据放入到缓存当中,当我需要10--20之 间的数据的时候,我的发现我的这些数据已经在我的缓存种存在了,我就直接存缓存中把数据读出来,少了一次查询,速度自然也提高了很多. 如果我访问第六页的数据,我就把我的缓存更新一次.这样连续翻页10次才进行两次IO操作同时又保证了内存不容易被溢出.而具体缓存设置多少,要看你的服务器的能力和访问的人数来决定。
下面是一个示例程序没有做缓存,缓存的部分可以自己实现,也可以选择ehcache等开源的实现。
程序结构如下:
- public class TestPagation {
-
- public void paginationQuery(String keyWord, int pageSize, int currentPage)
- throws ParseException, CorruptIndexException, IOException {
- String[] fields = { "title", "content" };
- // 创建一个分词器,和创建索引时用的分词器要一致
- Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
-
- QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_36,
- fields, analyzer);
- Query query = queryParser.parse(keyWord);
-
- // 打开索引目录
- File indexDir = new File("./indexDir");
- Directory directory = FSDirectory.open(indexDir);
-
- IndexReader indexReader = IndexReader.open(directory);
- IndexSearcher indexSearcher = new IndexSearcher(indexReader);
-
- // TopDocs 搜索返回的结果
- TopDocs topDocs = indexSearcher.search(query, 100);// 只返回前100条记录
- int totalCount = topDocs.totalHits; // 搜索结果总数量
- ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 搜索返回的结果集合
-
- // 查询起始记录位置
- int begin = pageSize * (currentPage - 1);
- // 查询终止记录位置
- int end = Math.min(begin + pageSize, scoreDocs.length);
-
- // 进行分页查询
- for (int i = begin; i < end; i++) {
- int docID = scoreDocs[i].doc;
- Document doc = indexSearcher.doc(docID);
- int id = NumericUtils.prefixCodedToInt(doc.get("id"));
- String title = doc.get("title");
- System.out.println("id is : " + id);
- System.out.println("title is : " + title);
- }
-
- }
-
- public static void main(String[] args) throws CorruptIndexException, ParseException, IOException {
- TestPagation t = new TestPagation();
- //每页显示5条记录,显示第三页的记录
- t.paginationQuery("RUNNING",5,3);
- }
-
- }
复制代码
[源码下载]
资料来源:http://www.cnblogs.com/skyme/archive/2012/08/02/2618341.html
|