如何发送弹性搜索查询结果的响应api?

2024-04-20 00:57:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个Elasticsearch查询,它提供了正确的结果,现在我想将结果作为搜索API的响应发送。你知道吗

我已经试着回复了

return JsonResponse(response, status=200)
return Response(response, safe=False) #error response is not JSON serializable
return HttpResponse(
            json.dumps(
                {"key": response.title}
            ),
            status=200,
            content_type="application/json"
        ) #AttributeError: 'Response' object has no attribute 'title'

我的代码

def search(request):
    if request.method=='GET':
        q = request.GET.get('q')

        if q:
            p = Q("multi_match", query=q, fields=['title', 'preview_path'])
            s = PostDocument.search().query(p)
            response = s.execute()
        else:
            response = ''

        return HttpResponse(response)

我的邮政编码

posts = Index('media')


@posts.doc_type
class PostDocument(DocType):
    print('documents.py')

    class Meta:
        model = Media
        fields = [
            'title',
            'description',
            'start_date',
            'end_date',
            'status',
            'media_source',
            'on_front_page',
            'thumbnail_path',
            'preview_path',
            'published_date',
            'created_at',
            'updated_at',
        ]

预期结果: 我想以Json响应的形式发送响应。你知道吗

实际结果,当我使用 打印(响应)

<Response: [{'start_date': datetime.datetime(2019, 1, 30, 0, 0), 'status...}]>

Tags: pathjsonsearchgetdatereturniftitle
1条回答
网友
1楼 · 发布于 2024-04-20 00:57:19

您可以使用json.dumps文件地址:

HttpResponse(
    json.dumps(
        {"key": response.key}
    ),
    status=200,
    content_type="application/json"
)

编辑:由于响应对象不是对象而是对象列表,因此需要执行以下操作:

response_list = []
for item in response:
    response_list.add(
        {
            "title": item.title,
            "description": item.description
        }
    )

return HttpResponse(
    json.dumps(response_list),
    status=200,
    content_type="application/json"
)

相关问题 更多 >