调整Elasticsearch的相关性得分

时间:2019-05-04 00:48:19

标签: python django elasticsearch django-haystack relevance

我目前正在使用Django-HaystackElasticsearch在Django项目中设置搜索功能,我想知道是否有任何方法可以更改搜索结果的相关性。

例如,我可以输入一个查询目标值的查询,例如Las+Vegas,它可以正常工作,但是当我得到结果时,我可以看到对应于另一个目标的查询对象,例如{{1} }。

那我该怎么做才能得到与指定目的地完全匹配的结果呢?

我的模特:

Laos

我正在使用这样的自定义form.py:

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

    ptags = TaggableManager()

    image = models.ImageField(default='')
    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 __str__(self):
        return self.destination

将自定义表单传递到Views.py:

from haystack.forms import FacetedSearchForm


class FacetedProductSearchForm(FacetedSearchForm):

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

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

        if self.ptag:
            query = None
            for ptags in self.ptag:
                if query:
                    query += u' OR '
                else:
                    query = u''
                query += u'"%s"' % sqs.query.clean(ptags)
            sqs = sqs.narrow(u'ptags_exact:%s' % query)

        return sqs

我的Urls.py:

class FacetedSearchView(BaseFacetedSearchView):

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

最后,我的search_indexes.py:

from django.conf.urls import url
from django.contrib import admin
from search.views import HomeView, ProductView, FacetedSearchView, autocomplete
from .settings import MEDIA_ROOT, MEDIA_URL
from django.conf.urls.static import static

urlpatterns = [
    url(r'^$', HomeView.as_view()),
    url(r'^admin/', admin.site.urls),
    url(r'^product/(?P<slug>[\w-]+)/$', ProductView.as_view(), name='product'),
    url(r'^search/autocomplete/$', autocomplete),
    url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'),

] + static(MEDIA_URL, document_root=MEDIA_ROOT)

谢谢。

0 个答案:

没有答案