【问题标题】:Haystack: Highlight only one fieldHaystack:仅突出显示一个字段
【发布时间】:2015-02-23 15:53:10
【问题描述】:

我正在使用 Haystack 2.3.0,并且我的搜索索引如下:

class MyModelIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    name = indexes.EdgeNgramField(model_attr='name', boost=1.250)
    short_description = indexes.CharField(model_attr='short_description', null=True, boost=1.125)
    description = indexes.CharField(model_attr='description', null=True, boost=1.125)
    detail_description = indexes.CharField(model_attr='detail_description', null=True)

    def get_model(self):
        return MyModel

我只想突出显示字段 detail_description。我读过official documentation 这个例子:

sqs = SearchQuerySet().filter(content='foo').highlight()
result = sqs[0]
result.highlighted['text'][0]

但是当我尝试这样做时,我没有得到相同的结果。在上面的示例中,result.highlighted 似乎是一个字典,您可以在其中访问每个字段的突出显示:

result.highlighted['text'][0]

但在我的示例中,当我这样做时,result.highlighted 不是字典,它是一个列表,并且只返回 text 字段的突出显示。

  • 如何将突出显示设置为具体字段?

【问题讨论】:

    标签: django elasticsearch highlight django-haystack


    【解决方案1】:

    如果 number_of_fragments 值设置为 0,则没有片段 产生,而是返回该字段的全部内容,并且 当然它被突出显示。如果短文本(如 文件标题或地址)需要突出显示但没有碎片 是必须的。请注意,在这种情况下,fragment_size 会被忽略。

    来自

    链接-http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-highlighting.html

    你需要看看如何在haystack中更改这个参数。

    【讨论】:

    • 所以,number_of_fragments 似乎是 0 并且因为 ElasticSearch 只返回 1 个字段?感谢您为我指明了正确的方向,我将深入研究 Haystack 文档
    • 当然,我猜它应该在 highlight() 函数调用中
    • Haystack 文档说高亮函数调用没有收到任何参数!但是感谢您帮助我了解为什么会发生这种情况!
    【解决方案2】:

    我现在的临时解决方案是做一个 for 循环并手动将高亮添加到字段中,如下所示:

    for result in sqs:
        highlight = Highlighter(my_query)  # my_query has the word(s) of the query
        result.detail_description = highlight.highlight(result.detail_description)
    

    【讨论】:

      【解决方案3】:

      这里有点晚了,但是如果你想传递额外的参数来突出显示,你需要传递一个弹性搜索想要用于突出显示功能的任何参数的字典,如下所示:

      # Solr example since I'm not familiar with ES
      sqs = SearchQuerySet().filter(content='foo').highlight(**{'hl.fl': 'short_description')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-21
        • 2012-05-11
        • 1970-01-01
        • 2010-12-25
        • 1970-01-01
        • 2012-12-01
        • 1970-01-01
        相关资源
        最近更新 更多