【问题标题】:How to exclude unrelated search results from django-haystack and Elasticsearch?如何从 django-haystack 和 Elasticsearch 中排除不相关的搜索结果?
【发布时间】:2017-12-12 17:14:33
【问题描述】:

我正在尝试根据关键字搜索产品。我的haystack索引如下:

class ProductIndex(indexes.SearchIndex, indexes.Indexable):
    name= indexes.CharField(model_attr='name')
    text = indexes.CharField(document=True) # contains keywords associated with the product

在这种情况下,“文本”字段包含一组与产品相关的关键字。例如,这是一个示例产品索引:

name: "Tide Detergent"
text: "laundry household shopping cleaning supplies"

当我搜索laundry 时,Tide Detergent 会出现在搜索中,但其他不相关的结果也会出现,例如text 中包含lawnlaugh 的产品。所以看起来elasticsearch 不仅在搜索laundry,还在搜索这个词的变体。

这是我的搜索查询的样子:

qs = SearchQuerySet().models(Product).filter(content__exact='laundry')

我的问题是:如何强制 haystackelasticsearch 严格搜索我的输入关键字并忽略它们的变体?换句话说,如何确保 haystack 只搜索 laundry 而排除任何其他术语?

【问题讨论】:

标签: django elasticsearch indexing full-text-search django-haystack


【解决方案1】:

我找到了答案。我使用了原始的elasticsearch 查询,而不是直接通过haystack。在那个查询中,我使用了 constant_score 查询,它将搜索 exact 术语,而不是模糊术语。

{
    "query":{
        "query":{
            "constant_score":{
                "filter":{
                    "bool":{
                        "must":[
                            {"bool":{
                                    "must":[
                                        {
                                            "term": {
                                                "text":"laundry"
                                            }
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            }
        }
    }
}

以下是有关constant_score 查询的更多信息:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-constant-score-query.html

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 2015-11-26
    • 2015-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多