How to get data from the query set returned from elasticsearch django

时间:2018-12-27 13:01:56

标签: python django elasticsearch

I am trying to get data from elastic search in my application but its returning a query set which triggers an error in my serializers "Expected a list of items but got type \"Search\".". And when I print results returned from elastic search i get <django_elasticsearch_dsl.search.Search object at 0x1101f2b00>. I haven't used elastic search before and its giving hell...

document.py

from django_elasticsearch_dsl import DocType, Index, fields
from elasticsearch_dsl import analyzer

from .models import Unit, Rental

units = Index('units')


html_strip = analyzer(
    'html_strip',
    tokenizer="standard",
    filter=["standard", "lowercase", "stop", "snowball"],
    char_filter=["html_strip"]
)


@units.doc_type
class UnitDocument(DocType):
    rental = fields.ObjectField(properties={
        'property_type': fields.TextField(),
        'city': fields.TextField(),
    })

    class Meta:
        model = Unit

        fields = [
            'bedroom',
            'bathroom',
            'price',
        ]
        related_models = [Rental]

    def get_queryset(self):
        """Not mandatory but to improve performance we can select related in one sql request"""
        return super(UnitDocument, self).get_queryset().select_related(
        'rental'
        )

    def get_instances_from_related(self, related_instance):
        """If related_models is set, define how to retrieve the unit instance(s) from the related model.
    The related_models option should be used with caution because it can lead in the index
    to the updating of a lot of items.
    """
        if isinstance(related_instance, Rental):
            return related_instance.car_set.all()

In my views.py i have tried to capture the anticipated data.

views.py

class SearchView(APIView):
    permission_classes = (AllowAny,)

    def get(self, request):
        query_price = request.query_params.get('budget')
        query_bedroom = request.query_params.get('bed')
        query_bathroom = request.query_params.get('bathroom')
        query_city = request.query_params.get('city')
        query_type = request.query_params.get('type')

        query_obj = {
            'price': query_price,
            'city': query_city,
            'bathroom': query_bathroom,
            'bedroom': query_bedroom,
            'property_type': query_type
        }

        if query_obj:
            search_results = UnitDocument.search().query("match", price=query_price)
            serializers = UnitSerializer(data=search_results, many=True)
            if serializers.is_valid(raise_exception=True):
                return Response(serializers.data, status=status.HTTP_200_OK)
        else:
            all_units = Unit.objects.all()
            serializers = UnitSerializer(data=all_units)
            if serializers.is_valid():
                return Response(serializers.data, status=status.HTTP_200_OK)

setting.py

# Django Elasticsearch integration
'django_elasticsearch_dsl',
# Django REST framework Elasticsearch integration (this package)
'django_elasticsearch_dsl_drf',

3 个答案:

答案 0 :(得分:0)

我几乎不学习python,但这可能对您有所帮助。

Elasticsearch DSL

答案 1 :(得分:0)

在浏览了弹性搜索文档和类似文章的色调之后,我发现了本文Django tricks。关于如何解决这个问题,我有一些提示。弹性搜索返回的查询集可以循环获得所需的项目。我也很好奇如何处理关系。Django - Fast Search With Elasticsearch将提供一个很好的起点

答案 2 :(得分:0)

search_results.to_queryset() 应该可以正常工作,search_result 是一个可迭代对象,它返回带有模型字段的字典,它不是查询集,您也可以尝试 list(search_result),但我不确定