`
wjboy49
  • 浏览: 274561 次
  • 性别: Icon_minigender_1
  • 来自: 湖南岳阳
社区版块
存档分类
最新评论

Lucene-2.3.1 源代码阅读学习(38)

阅读更多

关于QueryParser。

QueryParser是用来解析用户输入的查询的,将用户的输入的短语进行分析,从而提交Query查询来实现检索。

QueryParser一共有三个构造方法,我们通过使用如下的构造方法:

public QueryParser(String f, Analyzer a) {
    this(new FastCharStream(new StringReader("")));
    analyzer = a;
    field = f;
}

指定一个检索的关键字(String类型)和一个分析器。

当然,要使得:建立索引所使用的Analyzer的集合包含使用上面构造方法使用的Analyzer,这样才能在解析出用户意图,得到词条之后,通过IndexSearcher检索索引库,将查询结果返回给用户。

先看一个简单的例子:

package org.shirdrn.lucene.learn;

import java.io.IOException;
import java.util.Date;

import net.teamhot.lucene.ThesaurusAnalyzer;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.LockObtainFailedException;

public class QueryParserTest {

private String path = "E:\\Lucene\\index";

public void createIndex(){
   IndexWriter writer;
   try {
    writer = new IndexWriter(path,new ThesaurusAnalyzer(),true);
    //writer = new IndexWriter(path,new StandardAnalyzer(),true);
   
    String valueA = "在新安全策略中配置的设置可能导致应用程序或服务出现兼容性问题。因此,在将新的安全策略应用于生产服务器之前,应对其进行全面的测试。";
    Field fieldA1 = new Field("contents",valueA,Field.Store.YES,Field.Index.TOKENIZED);
    Field fieldA2 = new Field("date","2008",Field.Store.YES,Field.Index.UN_TOKENIZED);
    Document docA = new Document();
    docA.add(fieldA1);
    docA.add(fieldA2);
   
    String valueB = "强烈建议您确保用于创建安全策略的原型计算机与要在服务级进行配置的目标服务器相匹配。";
    Field fieldB1 = new Field("contents",valueB,Field.Store.YES,Field.Index.TOKENIZED);
    Field fieldB2 = new Field("date","2002",Field.Store.YES,Field.Index.UN_TOKENIZED);
    Document docB = new Document();
    docB.add(fieldB1);
    docB.add(fieldB2);
   
    String valueC = "通过创建专为服务器的特定角色而设计的安全策略,SCW 有助于减小服务器的受攻击面。管理员可以通过识别执行相同或类似任务的服务器组来简化策略的创建和分发。";
    Field fieldC1 = new Field("contents",valueC,Field.Store.YES,Field.Index.TOKENIZED);
    Field fieldC2 = new Field("date","2006",Field.Store.YES,Field.Index.UN_TOKENIZED);
    Document docC = new Document();
    docC.add(fieldC1);
    docC.add(fieldC2);

    writer.addDocument(docA);
    writer.addDocument(docB);
    writer.addDocument(docC);
    writer.close();
   } catch (CorruptIndexException e) {
    e.printStackTrace();
   } catch (LockObtainFailedException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
}

public static void main(String[] args) {
   QueryParserTest queryParserTest = new QueryParserTest();
   queryParserTest.createIndex();    // 调用createIndex()方法建立索引
   try {
    String userKeyword = "服务器 date:2006";
    QueryParser queryParser = new QueryParser("contents",new ThesaurusAnalyzer());
    //QueryParser queryParser = new QueryParser("contents",new StandardAnalyzer());
    queryParser.setDefaultOperator(QueryParser.AND_OPERATOR);    // 使用了AND_OPERATOR
    Query query = queryParser.parse(userKeyword);
    System.out.println("解析用户输入关键字 : "+query.toString());
    IndexSearcher searcher = new IndexSearcher(queryParserTest.path);
    Date startTime = new Date();
    Hits hits = searcher.search(query);
    System.out.println("********************************************************************");
    for(int i=0;i<hits.length();i++){
     System.out.println("Document的内部编号为 : "+hits.id(i));
     System.out.println("Document内容为 : "+hits.doc(i));
     System.out.println("Document的得分为 : "+hits.score(i));
    }
    System.out.println("********************************************************************");
    System.out.println("共检索出符合条件的Document "+hits.length()+" 个。");
    Date finishTime = new Date();
    long timeOfSearch = finishTime.getTime() - startTime.getTime();
    System.out.println("本次搜索所用的时间为 "+timeOfSearch+" ms");
   } catch (ParseException e) {
    e.printStackTrace();
   } catch (CorruptIndexException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
  
}

}

从上面的程序中可以看出,String userKeyword = "服务器 date:2006";定义的就是用户提交的关键字,假设建立索引对应的是一些文章,包括文章内容和发表时间。

我们对这个假想的用户的检索意图进行分析:

他的服务器可能不是最新的也不是最早的服务器产品,“服务器”作为一个关键字字段,而且选择这样的文章的时间不能是最新的,也不能是最早的,中和一下选择2006年。

queryParser.setDefaultOperator(QueryParser.AND_OPERATOR);设置了将解析的用户查询进行AND组合,即取交集。

另外,对于时间,我们假设让用户指定Field的字段date,其实这也是很容易能办到的。

而且,建立索引和构造QueryParser的时候都使用了ThesaurusAnalyzer分析器。

运行程序,检索结果如下所示:

词库尚未被初始化,开始初始化词库.
初始化词库结束。用时:3703毫秒;
共添加195574个词语。
解析用户输入关键字 : +contents:服务器 +date:2006
********************************************************************
Document的内部编号为 : 2
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents:通过创建专为服务器的特定角色而设计的安全策略,SCW 有助于减小服务器的受攻击面。管理员可以通过识别执行相同或类似任务的服务器组来简化策略的创建和分发。> stored/uncompressed,indexed<date:2006>>
Document的得分为 : 1.0
********************************************************************
共检索出符合条件的Document 1 个。
本次搜索所用的时间为 250 ms

可见,QueryParser根据这样的理解去解析是非常符合用户的检索意向的,而且检索结果很精确。

同样,如果AND_OPERATOR操作符改为OR_OPERATOR操作符,可想而知,检索结果应该将含有关键字“服务器”或者关键字“2006”的结果检索出来,但是这样无疑将检索结果的范围扩大了,返回的结果一般来说较多。

如果将用户的检索关键字设置为:String userKeyword = "服务器安全配置";,用户因该是想对服务器进行配置,保证安全性,使用上面的程序检索,结果如下:

初始化词库结束。用时:4016毫秒;
共添加195574个词语。
解析用户输入关键字 : contents:"服务器 安全 配置"
********************************************************************
********************************************************************
共检索出符合条件的Document 0 个。
本次搜索所用的时间为 93 ms

可见,实际上建立索引的Document中含有这些关键字,却并不能检索出相应的结果。

用户在输入关键字的时候,如果想要表达这样一层含义:通过键入多个关键字,比如键入了“服务器 安全 配置 策略”,通过空格来间隔各个关键字,一般来说,这样的用户的检索意图是文章中包含这些键入的关键词,即各个关键词是AND关系,这样提交查询,会把所有的包含这些关键字的文章检索出来。

只要我们建立的索引库中具有丰富的能够满足用户检索意向的词条,都是能实现的。

例如,将用户键入的关键词设置为:

String userKeyword = "服务器 安全 配置 策略";

运行程序,检索结果如下所示:

词库尚未被初始化,开始初始化词库.
初始化词库结束。用时:3703毫秒;
共添加195574个词语。
解析用户输入关键字 : +contents:服务器 +contents:安全 +contents:配置 +contents:策略
********************************************************************
Document的内部编号为 : 1
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents:强烈建议您确保用于创建安全 策略 的原型计算机与要在服务级进行配置 的目标服务器 相匹配。> stored/uncompressed,indexed<date:2002>>
Document的得分为 : 0.29777634
Document的内部编号为 : 0
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents:在新安全 策略配置 的设置可能导致应用程序或服务出现兼容性问题。因此,在将新的安全 策略 应用于生产服务器 之前,应对其进行全面的测试。> stored/uncompressed,indexed<date:2008>>
Document的得分为 : 0.28950247
********************************************************************
共检索出符合条件的Document 2 个。
本次搜索所用的时间为 94 ms

可见,QueryParser的理解是:

+contents:服务器 +contents:安全 +contents:配置 +contents:策略

用户就是要检索全部包含这四个关键字的文章,最重要的程序中指定了:

queryParser.setDefaultOperator(QueryParser.AND_OPERATOR);

各个关键字之间是AND的关系,因为Lucene默认值为OR关系,倘若不设置为AND_OPERATOR,只要文章中出现上面的莫个关键字,就被认为是检索结果,例如使用上面的.setDefaultOperator()设置为OR_OPERATOR或者不设置使用默认的就是这种设置,检索结果如下:

词库尚未被初始化,开始初始化词库.
初始化词库结束。用时:3672毫秒;
共添加195574个词语。
解析用户输入关键字 : contents:服务器 contents:安全 contents:配置 contents:策略
********************************************************************
Document的内部编号为 : 1
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents:强烈建议您确保用于创建安全策略的原型计算机与要在服务级进行配置的目标服务器相匹配。> stored/uncompressed,indexed<date:2002>>
Document的得分为 : 0.29777637
Document的内部编号为 : 0
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents:在新安全策略中配置的设置可能导致应用程序或服务出现兼容性问题。因此,在将新的安全策略应用于生产服务器之前,应对其进行全面的测试。> stored/uncompressed,indexed<date:2008>>
Document的得分为 : 0.28950244
Document的内部编号为 : 2
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents:通过创建专为服务器的特定角色而设计的安全策略,SCW 有助于减小服务器的受攻击面。管理员可以通过识别执行相同或类似任务的服务器组来简化策略的创建和分发。> stored/uncompressed,indexed<date:2006>>
Document的得分为 : 0.15523766
********************************************************************
共检索出符合条件的Document 3 个。
本次搜索所用的时间为 125 ms

使用QueryParser解析后得到的Query的值为:

解析用户输入关键字 : contents:服务器 contents:安全 contents:配置 contents:策略

在内部通过空格指定各个Field的关系说明是OR关系,检索结果一般来说较多。

通过上面的测试,我们可以得出这样一个结论:

用户在输入多个关键字的时候,使用“空格”将多个关键字间隔开,事实上这个“空格”实际指定了一个内部操作符,关键是在内部如何对QueryParser进行设置,如一般简单地设置为AND_OPERATOR,OR_OPERATOR。

其实,在Lucene中定义了多种操作符,在QueryParser内部实现中,主以通过一些getter方法来看出,例如关于Wildcard通配符查询的:

protected Query getWildcardQuery(String field, String termStr) throws ParseException
{
    if ("*".equals(field)) {
      if ("*".equals(termStr)) return new MatchAllDocsQuery();
    }
    if (!allowLeadingWildcard && (termStr.startsWith("*") || termStr.startsWith("?")))
      throw new ParseException("'*' or '?' not allowed as first character in WildcardQuery");
    if (lowercaseExpandedTerms) {
      termStr = termStr.toLowerCase();
    }
    Term t = new Term(field, termStr);
    return new WildcardQuery(t);
}

可以在键入关键字的时候,指定通配符,QueryParser能够解析出用户使用通配符的检索意图。比如,使用下面关键字检索:

String userKeyword = "文?武?";

将前面的测试程序中createIndex()建立索引的方法修改为如下:

public void createIndex(){
   IndexWriter writer;
   try {
    writer = new IndexWriter(path,new ThesaurusAnalyzer(),true);
    
    Field fieldA = new Field("contents","文人",Field.Store.YES,Field.Index.TOKENIZED);
    Document docA = new Document();
    docA.add(fieldA);
   
    Field fieldB = new Field("contents","文修武偃",Field.Store.YES,Field.Index.TOKENIZED);
    Document docB = new Document();
    docB.add(fieldB);
   
    Field fieldC = new Field("contents","文东武西",Field.Store.YES,Field.Index.TOKENIZED);
    Document docC = new Document();
    docC.add(fieldC);
   
    Field fieldD = new Field("contents","不使用武力",Field.Store.YES,Field.Index.TOKENIZED);
    Document docD = new Document();
    docD.add(fieldD);
   
    Field fieldE = new Field("contents","不文不武",Field.Store.YES,Field.Index.TOKENIZED);
    Document docE = new Document();
    docE.add(fieldE);

    writer.addDocument(docA);
    writer.addDocument(docB);
    writer.addDocument(docC);
    writer.addDocument(docD);
    writer.addDocument(docE);
   
    writer.close();
   } catch (CorruptIndexException e) {
    e.printStackTrace();
   } catch (LockObtainFailedException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
}

然后,运行程序,检索结果如下所示:

解析用户输入关键字 : contents:文?武?
********************************************************************
Document的内部编号为 : 1
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents: 偃>>
Document的得分为 : 1.0
Document的内部编号为 : 2
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents: 西>>
Document的得分为 : 1.0
********************************************************************
共检索出符合条件的Document 2 个。
本次搜索所用的时间为 94 ms

从检索结果可以看出:

解析用户输入关键字 : contents:文?武?

QueryParser的解析结果认为,这需要使用WildcardQuery。

QueryParser也能解析Fuzzy查询,例如,检索关键字为:

String userKeyword = "文东武西~0.01";

检索结果如下所示:

解析用户输入关键字 : contents:文东武西~0.01
********************************************************************
Document的内部编号为 : 2
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents:文东武西>>
Document的得分为 : 0.99999994
Document的内部编号为 : 1
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents:文修武偃>>
Document的得分为 : 0.4949495
Document的内部编号为 : 4
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents:不文不武>>
Document的得分为 : 0.24242423
********************************************************************
共检索出符合条件的Document 3 个。
本次搜索所用的时间为 109 ms

由于使用的最小严格程度接近于0,表示极其不严格匹配,所以Fuzzy检索结果较多。提高最小严格度,可以提高检索匹配的精度,比如使用:

String userKeyword = "文东武西~0.62";

检索结果如下:

解析用户输入关键字 : contents:文东武西~0.62
********************************************************************
Document的内部编号为 : 2
Document内容为 : Document<stored/uncompressed,indexed,tokenized<contents:文东武西>>
Document的得分为 : 1.0
********************************************************************
共检索出符合条件的Document 1 个。
本次搜索所用的时间为 156 ms

在前面的使用QueryParser的例子中,出现这样的字样:

“词库尚未被初始化,开始初始化词库.
初始化词库结束。用时:3688毫秒;
共添加195574个词语。

说明,对用户输入的关键字进行了分词,而后面的测试中,我们输入的就是词库中已经存在的词条,并没有对用户输入的关键字做任何分词处理,亦即,在下面构造QueryParser的时候:

QueryParser queryParser = new QueryParser("contents",new ThesaurusAnalyzer());

实例化的ThesaurusAnalyzer分析器实例并没有执行分词操作,根本不需要分词。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics