gpt4 book ai didi

python - 如何从elasticsearch django返回的查询集中获取数据

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:35 25 4
gpt4 key购买 nike

我正在尝试从应用程序中的 Elasticsearch 获取数据,但它返回一个查询集,这会在我的序列化器中触发错误 "Expected a list of items but got type \"Search\"." 。当我打印从 Elasticsearch 返回的结果时,我得到 <django_elasticsearch_dsl.search.Search object at 0x1101f2b00> 。我以前没有使用过 Elasticsearch ,它给我带来了 hell ......

文档.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()

在我的views.py中,我 try catch 预期的数据。

View .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)

设置.py

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

最佳答案

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

关于python - 如何从elasticsearch django返回的查询集中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53945542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com