【问题标题】:Django-Haystack not returning exact queryDjango-Haystack 没有返回准确的查询
【发布时间】:2019-12-13 10:33:11
【问题描述】:

我正在尝试修复我的 Django-haystack 并结合 Elasticsearch 搜索结果准确。

我现在遇到的问题是,例如,当用户尝试“Mexico”查询时,搜索结果还会返回“Melbourne”中的交易,这远非用户友好。

谁能帮我解决这个问题?

这是我迄今为止尝试过但没有好的结果:

我的表单.py

from haystack.forms import FacetedSearchForm
from haystack.inputs import Exact


class FacetedProductSearchForm(FacetedSearchForm):

    def __init__(self, *args, **kwargs):
        data = dict(kwargs.get("data", []))
        self.ptag = data.get('ptags', [])
        self.q_from_data = data.get('q', '')
        super(FacetedProductSearchForm, self).__init__(*args, **kwargs)

    def search(self):
        sqs = super(FacetedProductSearchForm, self).search()

        # Ideally we would tell django-haystack to only apply q to destination
        # ...but we're not sure how to do that, so we'll just re-apply it ourselves here.
        q = self.q_from_data
        sqs = sqs.filter(destination=Exact(q))

        print('should be applying q: {}'.format(q))
        print(sqs)

        if self.ptag:
            print('filtering with tags')
            print(self.ptag)
            sqs = sqs.filter(ptags__in=[Exact(tag) for tag in self.ptag])

        return sqs

我的 search_indexes.py

import datetime
from django.utils import timezone
from haystack import indexes
from haystack.fields import CharField

from .models import Product


class ProductIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(
        document=True, use_template=True,
        template_name='search/indexes/product_text.txt')
    title = indexes.CharField(model_attr='title')
    description = indexes.EdgeNgramField(model_attr="description")
    destination = indexes.EdgeNgramField(model_attr="destination") #boost=1.125
    link = indexes.CharField(model_attr="link")
    image = indexes.CharField(model_attr="image")

    # Tags
    ptags = indexes.MultiValueField(model_attr='_ptags', faceted=True)

    # for auto complete
    content_auto = indexes.EdgeNgramField(model_attr='destination')

    # Spelling suggestions
    suggestions = indexes.FacetCharField()

    def get_model(self):
        return Product

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.filter(timestamp__lte=timezone.now())

我的模型.py

class Product(models.Model):
    destination = models.CharField(max_length=255, default='')
    title = models.CharField(max_length=255, default='')
    slug = models.SlugField(unique=True, max_length=255)
    description = models.TextField(max_length=2047, default='')
    link = models.TextField(max_length=500, default='')

    ptags = TaggableManager()

    image = models.ImageField(max_length=500, default='images/zero-image-found.png')
    timestamp = models.DateTimeField(auto_now=True)

    def _ptags(self):
        return [t.name for t in self.ptags.all()]

    def get_absolute_url(self):
        return reverse('product',
                       kwargs={'slug': self.slug})

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = slugify(self.title)
        super(Product, self).save(*args, **kwargs)


    def __str__(self):
        return self.destination

还有我的观点.py

from haystack.generic_views import FacetedSearchView as BaseFacetedSearchView
from .forms import FacetedProductSearchForm

class FacetedSearchView(BaseFacetedSearchView):

    form_class = FacetedProductSearchForm
    facet_fields = ['ptags']
    template_name = 'search_result.html'
    paginate_by = 30
    context_object_name = 'object_list'

谢谢。

【问题讨论】:

    标签: python json django elasticsearch django-haystack


    【解决方案1】:

    您的问题在于您使用dict.get

    self.q_from_data = data.get('q', [''])[0]
    

    例如

    data.get('q')  # This will return the string "Mexico"
    data.get('q')[0]  # This will return the first letter "M"
    

    该行应该是

    self.q_from_data = data.get('q', '')
    

    【讨论】:

    • 感谢您的快速回答@lain,我马上试试。
    • 我应该在那之后运行任何命令吗?像 python manage.py update_index
    • 您只需要重新加载应用程序
    • 我在墨尔本仍然得到结果
    • 尝试将super().__init__ 作为第一行并在之后调用您的自定义代码
    【解决方案2】:

    我刚刚找到了解决这个问题的方法。如果您想通过悬赏同一问题来避免失去任何声誉,请听好。

    基本上,我必须将我的 search_indexes.py 文档中的原始 destination 字段替换为以下行:

    来自:destination = indexes.EdgeNgramField(model_attr="destination")

    对此:destination = indexes.CharField(model_attr="destination")

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 2013-04-28
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多