django - 超过 245 个字符长度的 Xapian 搜索词 : InvalidArgumentError: Term too long (> 245)

标签 django django-haystack xapian

我在我的 django 应用程序中使用 Xapian 和 Haystack。我有一个模型,其中包含我想要索引以进行搜索的文本字段。该字段用于存储各种字符:words、urls、html等。

我正在使用默认的基于文档的索引模板:

text = indexes.CharField(document=True, use_template=True)

当有人粘贴了一个特别长的链接时,这有时会产生以下错误:
InvalidArgumentError: Term too long (> 245)

现在我明白了这个错误。我之前已经在其他情况下的其他领域解决了这个问题。

我的问题是,处理此异常的首选方法是什么?

似乎处理这个异常需要我使用一个 prepare_text() 方法:
def prepare_text(self, obj):
    content = []      
    for word in obj.body.split(' '):
        if len(word) <= 245:
            content += [word]
    return ' '.join(content)

它只是看起来笨重并且容易出现问题。另外我不能使用搜索模板。

你是如何处理这个问题的?

最佳答案

我认为你做对了。在inkscape 上有一个补丁xapian_backend fork,灵感来自 xapian omega 项目。

我已经做了一些类似于你在我的项目中所做的事情,并使用了一些技巧来使用搜索索引模板:

# regex to efficiently truncate with re.sub
_max_length = 240
_regex = re.compile(r"([^\s]{{{}}})([^\s]+)".format(_max_length))

def prepare_text(self, object):

    # this is for using the template mechanics
    field = self.fields["text"]
    text = self.prepared_data[field.index_fieldname]

    encoding = "utf8"
    encoded = text.encode(encoding)

    prepared = re.sub(_regex, r"\1", encoded, re.UNICODE)

    if len(prepared) != len(encoded):
        return prepared.decode(encoding, 'ignore')

    return text

关于django - 超过 245 个字符长度的 Xapian 搜索词 : InvalidArgumentError: Term too long (> 245),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30925487/

相关文章:

python - Django - 无法在下拉列表中检索数据库中的数据

python - django haystack/whoosh : find records with umlauts/diaeresis, 带有简单的 ascii 查询

Qt + xapian 库

django - Django 的 Haystack 是什么?

python - geodjango + PostGIS = GPL?

python - Django模板,如何制作一个选择了预定义值的下拉框?

django - 如何使用 Elasticsearch 通过 Haystack 使用 JSON 查询?

lucene - 部分词的文档搜索

python - 手动设置models.DateTimeField

python - Django 将 Haystack 荧光笔结果传递给 View