Search code examples
pythonelasticsearchelasticsearch-dsl

elasticsearch-dsl-py query formation


can someone show me how to frame this example query using this dsl python module?

I have only so far something like for a portion of the query string.

from elasticsearch_dsl import Search, Q, A, query, aggs
s = Search()
s.aggs.bucket('2', 'terms', field = 'Subscriber Type', size=5)

I'm not sure how the syntax is for the rest of the query. Any help is much appreciated.

The required query construction is below.

{
   "size": 0,
   "query": {
   "filtered": {
   "query": {
    "query_string": {
      "query": "lincoln",
      "analyze_wildcard": true
    }
  },
  "filter": {
    "bool": {
      "must": [
        {
          "range": {
            "Start date": {
              "gte": 936157359664,
              "lte": 1472701359665,
              "format": "epoch_millis"
            }
          }
        }
      ],
      "must_not": []
    }
  }
}
},
 "aggs": {
 "2": {
    "terms": {
    "field": "Subscriber Type",
    "size": 5,
    "order": {
      "_count": "desc"
    }
  },
  "aggs": {
    "3": {
      "terms": {
        "field": "Start Station",
        "size": 5,
        "order": {
          "_count": "desc"
        }
       }
      }
     }
    }
   }
  }

Solution

  • This should do the trick:

    s = Search()
    s = s.query("query_string", query="lincoln", analyze_wildcard=True)
    s = s.filter("range", **{"Start date": {"gte": 936157359664, "lte": 1472701359665, "format": "epoch_millis"}})
    s = s[0:0]
    s.aggs.bucket("2", "terms", field="Subscriber Type", size=5)\
        .bucket("3", "terms", field="Start Station", size=5)
    

    Note that the spaces in field names make things a tiny bit more complicated, without them you could say: s.filter("range", start_date={"gte": 936157359664, "lte": 1472701359665, "format": "epoch_millis"}).