我有一些關于 Elasticsearch 的資料并使用 Fastapi GET 呼叫檢索資料。
我使用下面的代碼從 Elasticsearch 獲取資料
主檔案
@app.get("/get_all")
def getData():
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
es.indices.refresh(index="fraction")
res = es.search(index="fraction", body={"query": {"match_all": {}}})
return res
它回傳這樣的資料
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 11,
"relation": "eq"
},
"max_score": 1,
"hits": [
{
"_index": "fraction",
"_type": "_doc",
"_id": "qx-PtoAB8NYsWRUHEO5X",
"_score": 1,
"_source": {
"company_name": "Fraction",
"floor": "Ground Floor",
"group ": "Group 1",
"camera": "Camera_1",
"videos": "video1"
}
}....
像這種格式一樣回傳資料,但我希望只回傳_source欄位(公司名稱,組....)。
我如何使用 Fastapi GET 呼叫來做到這一點。
uj5u.com熱心網友回復:
您需要將 Elasticsearch 的回應轉換為您想要的物件:
這是一種方法:
@app.get("/get_all")
def getData():
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
es.indices.refresh(index="fraction")
res = es.search(index="fraction", body={"query": {"match_all": {}}})
hits = res.get("hits", {}).get("hits", [])
return {
"results": [hit.get("_source") for hit in hits]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475048.html
標籤:Python python-3.x 弹性搜索 快速API
