Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django Haystack未返回精确查询_Python_Json_Django_<img Src="//i.stack.imgur.com/RUiNP.png" Height="16" Width="18" Alt="" Class="sponsor Tag Img">elasticsearch_Django Haystack - Fatal编程技术网 elasticsearch,django-haystack,Python,Json,Django,elasticsearch,Django Haystack" /> elasticsearch,django-haystack,Python,Json,Django,elasticsearch,Django Haystack" />

Python Django Haystack未返回精确查询

Python Django Haystack未返回精确查询,python,json,django,elasticsearch,django-haystack,Python,Json,Django,elasticsearch,Django Haystack,我正试图将Django haystack与Elasticsearch搜索结果结合起来,使其准确无误 我现在遇到的问题是,当用户尝试“墨西哥”查询时,搜索结果也会返回“墨尔本”的交易,这远不是用户友好的 有人能帮我解决这个问题吗 这是我到目前为止尝试过的,但没有好结果: 我的表格.py from haystack.forms import FacetedSearchForm from haystack.inputs import Exact class FacetedProductSearch

我正试图将Django haystack与Elasticsearch搜索结果结合起来,使其准确无误

我现在遇到的问题是,当用户尝试“墨西哥”查询时,搜索结果也会返回“墨尔本”的交易,这远不是用户友好的

有人能帮我解决这个问题吗

这是我到目前为止尝试过的,但没有好结果:

我的表格.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
我的搜索索引.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())
我的模特

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'

谢谢。

您的问题在于使用
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', '')

我刚刚找到了这个问题的解决办法。如果你想避免在同一个问题上悬赏而失去任何声誉,请倾听

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

由此:
destination=index.EdgeNgramField(model\u attr=“destination”)


对此:
destination=index.CharField(model\u attr=“destination”)

谢谢您的快速回答@lain,我马上就要尝试了。之后我应该运行任何命令吗?像python manage.py update\u indexy一样,您只需要重新加载应用程序,然后在MelbourneTry中调用
super()