首页 > 解决方案 > 我们如何使用弹性搜索在 django rest 框架中获得热门搜索列表?

问题描述

我正在使用 django 2.1、弹性搜索 6.1 和 django-elasticsearch-dsl-drf 0.17.6。

视图.py

class SchoolViewSet(DocumentViewSet):
    document = SchoolDocument
    serializer_class = SchoolDocumentSerializer
    permission_classes = (AllowAny,)

    lookup_field = 'id'
    filter_backends = [
        FilteringFilterBackend,
        CompoundSearchFilterBackend,
        FacetedSearchFilterBackend
    ]

    # Define ordering fields
    ordering_fields = {
        'name': 'name',
    }

    # Specify default ordering
    ordering = ('name',)

    faceted_search_fields = {
        'top_name_hit': {
            'field': 'name',
            'facet': TermsFacet,
            'enabled': True,
            'options': {
                'size': 4,  # Override default number of suggestions
                "order": {"_count": "desc"},
                'show_term_doc_count_error': True,
            },

        },
    }

文件.py

@INDEX.doc_type
class InstituteDocument(DocType):
    id = fields.StringField(attr='id_str')
    name = fields.StringField(
        analyzer=html_strip,
        fields={
            'raw': KeywordField(),
            'suggest': fields.CompletionField(),
            'edge_ngram_completion': fields.StringField(
                analyzer=edge_ngram_completion
            ),
        },
        fielddata=True
    )
    class Meta:
        model = School

我想获得搜索量最高的学校的结果。我怎样才能获得热门列表的列表?

标签: pythondjangoelasticsearchsearchdjango-rest-framework

解决方案


如果你想得到top size的文件,你需要按你的字段排序,如果你想得到一些学校文件,你需要使用学校过滤。如果你找不到这些方法,试试看django es dsl drf源代码 。 https://github.com/sabricot/django-elasticsearch-dsl

因为不允许我写commnet,所以我在这里写。


推荐阅读