【问题标题】:Apache Lucene: How to use TokenStream to manually accept or reject a token when indexingApache Lucene:如何在索引时使用 TokenStream 手动接受或拒绝令牌
【发布时间】:2017-01-28 04:49:47
【问题描述】:

我正在寻找一种使用 Apache Lucene 编写自定义索引的方法(准确地说是 PyLucene,但 Java 的答案很好)。

我想做的是:当将文档添加到索引中时,Lucene 会对其进行标记,删除停用词等。如果我没记错的话,通常使用Analyzer 来完成。

我想要实现的是以下内容:在 Lucene 存储给定术语之前,我想执行查找(例如,在字典中)以检查是保留该术语还是丢弃它(如果存在该术语在我的字典中,我保留它,否则我丢弃它)。

我应该如何进行?

这是(在 Python 中)我对 Analyzer 的自定义实现:

class CustomAnalyzer(PythonAnalyzer):

    def createComponents(self, fieldName, reader):

        source = StandardTokenizer(Version.LUCENE_4_10_1, reader)
        filter = StandardFilter(Version.LUCENE_4_10_1, source)
        filter = LowerCaseFilter(Version.LUCENE_4_10_1, filter)
        filter = StopFilter(Version.LUCENE_4_10_1, filter,
                            StopAnalyzer.ENGLISH_STOP_WORDS_SET)

        ts = tokenStream.getTokenStream()
        token = ts.addAttribute(CharTermAttribute.class_)
        offset = ts.addAttribute(OffsetAttribute.class_)

        ts.reset()

         while ts.incrementToken():
           startOffset = offset.startOffset()
           endOffset = offset.endOffset()
           term = token.toString()
           # accept or reject term 

         ts.end()
         ts.close()

           # How to store the terms in the index now ?

         return ????

提前感谢您的指导!

编辑 1:在深入研究 Lucene 的文档后,我认为它与 TokenStreamComponents 有关。它返回一个 TokenStream,您可以使用它遍历您正在索引的字段的 Token 列表。

现在我不明白与Attributes 有关。或者更准确地说,我可以读取令牌,但不知道接下来应该如何进行。

EDIT 2:我发现了这个post,他们提到了CharTermAttribute 的使用。但是(尽管在 Python 中)我无法访问或获取CharTermAttribute。有什么想法吗?

EDIT3:我现在可以访问每个术语,请参阅更新代码 sn-p。现在剩下要做的实际上是存储所需的术语...

【问题讨论】:

    标签: java python apache indexing lucene


    【解决方案1】:

    我试图解决问题的方式是错误的。 postfemtoRgon 的答案就是解决方案。

    通过定义扩展PythonFilteringTokenFilter 的过滤器,我可以使用函数accept()(例如StopFilter 中使用的函数)。

    这里是对应的代码sn-p:

    class MyFilter(PythonFilteringTokenFilter):
    
      def __init__(self, version, tokenStream):
        super(MyFilter, self).__init__(version, tokenStream)
        self.termAtt = self.addAttribute(CharTermAttribute.class_)
    
    
      def accept(self):
        term = self.termAtt.toString()
        accepted = False
        # Do whatever is needed with the term
        # accepted = ... (True/False)
        return accepted
    

    然后只需将过滤器附加到其他过滤器(如问题的代码所示):

    filter = MyFilter(Version.LUCENE_4_10_1, filter)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-28
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多