Lucene - Specialized TokenStream / Analyzer给出了一组可索引的关键字

时间:2013-07-07 09:13:41

标签: lucene

我有以下情况 我有一组索引文件。但我需要选择我的索引。

选择标准:文档必须包含给定Set中的一个关键字。

这部分很简单,我可以检查文档中是否存在这些关键字,然后才对文档编制索引。 棘手的情况是(对我来说无论如何!),我想只索引这些关键字。这些关键字也可以是多重的,也可以是正则表达式。

这些关键字对于这篇文章来说是没有意义的,因为我可以抽象出来 - 我可以生成需要编制索引的关键字列表。

我可以使用现有的TokenStream,Analyzer,Filter组合吗? 如果没有,请有人指出我正确的方向。


如果我的问题不够明确:

HashSet<String> impKeywords = new HashSet<String>(new String[] {"Java", "Lucene"});

我有一个课程Content,我会说:

Content content = new Content("I am only interested in Java, Lucene, Nutch, Luke, CommonLisp.");

并说,我有一种方法可以获得匹配的关键字:

HashSet<String> matchingKeywords = content.getMatchingKeywords(impKeywords); // returns a set with "Java" and "Lucene"

如果有匹配的关键字,则只进行索引文档;这样:

if(!matchingKeywords.isEmpty()) {
    // prepare document for indexing, and index.
    // But what should be my Analyzer and TokenStream?
}

我希望能够使用只返回这些匹配关键字的TokenStream创建一个Analyzer,因此只有这些标记被编入索引。

结束备注:似乎有一种可能性是,对于每个文档,我都会为每个匹配的关键字添加可变数量的字段。这些字段在哪里被索引但未使用Field.Index.NOT_ANALYZED进行分析。但是,如果我能够为此目的找出预先存在的Analyzer / TokenStream而不是使用字段,那会更好。

1 个答案:

答案 0 :(得分:0)

按照@ femtoRgon的建议我已经解决了上述问题如下。

如问题所述,我有:

HashSet<String> impKeywords = new HashSet<String>(new String[] {"Java", "Lucene"});

我使用了一个Content课程,如下所示:

Content content = new Content("I am only interested in Java, Lucene, Nutch, Luke, CommonLisp.");

而且,我有一种获取匹配关键字的方法:

HashSet<String> matchingKeywords = content.getMatchingKeywords(impKeywords); // returns a set with "Java" and "Lucene" for this example `content`.

如果有匹配的关键字,则只进行索引文档;所以在编制索引时我做了:

if(!matchingKeywords.isEmpty()) {
    Document doc = new Document();
    for(String keyword: matchingKeywords) {   
        doc.add(new Field("keyword", keyword, Field.Store.YES, Field.Index.NOT_ANALYZED);
    }
    iwriter.addDocument(doc); // iwriter is the instance of IndexWriter
}

然后,在搜索时我创建了以下布尔查询:

BooleanQuery boolQuery = new BooleanQuery();

for(String queryKeyword: searchKeywords)) {
    boolQuery.add(new TermQuery(new Term("keyword", queryKeyword)), BooleanClause.Occur.SHOULD);
}

ScoreDoc[] hits = isearcher.search(boolQuery, null, 1000).scoreDocs; // isearcher is the instance of IndexSearcher

希望这个答案可以帮助有类似需求的人。

相关问题