Home > Back-end >  Query with Elasticsearch and Return source field only
Query with Elasticsearch and Return source field only

Time:05-15

I have some data on Elasticsearch and retrieve data using Fastapi GET call.

i used below code to GET data from Elasticsearch

main.py

@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

it return data like this

{
  "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"
        }
      }....

Returned data like this format but i expected to return _source field (company_name , group ....) only.

how can i do this with Fastapi GET call.

CodePudding user response:

You need to transform Elasticsearch's response to the object that you want:

Here is one way to do it:

@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]
    }
  • Related