title: Elasticsearch DSL: filter, then aggregate in python
body: <p>I need to filter documents in an <code>Elasticsearch</code> index and then aggregate them by field. Here is the code of what I am trying to do:</p>
  
  <pre><code>import elasticsearch
  from elasticsearch_dsl import Search, Q, Index, MultiSearch
  es_client = elasticsearch.Elasticsearch([url],
          timeout=30, retry_on_timeout=True)
  project_ids=['CSI'] 
  family_ids=['SF6140691_WES_CIDR'] 
  sample_ids=['S1379354_CIDR'] 
  gene_symbols=['GLTPD1', 'CCNL2', 'MRPL20'] 
  
  genes_filter = Q('bool', must=[Q('terms', project_id=project_ids),
                                     Q('terms', family_id=family_ids),
                                     Q('terms', sample_id=sample_ids),
                                     Q('terms', gene_symbol=gene_symbols)])
  search = Search(using=es_client, index="GENES_DATA")
  search = search.filter(genes_filter).execute()
  results = search.aggs.bucket('by_family', 'terms', field='family_id', size=0)
  </code></pre>
  
  <p>Currently I am getting the following error:</p>
  
  <blockquote>
    <p>'{!r} object has no attribute {!r}'.format(self.<strong>class</strong>.<strong>name</strong>, name))
    AttributeError: 'Terms' object has no attribute 'execute'</p>
  </blockquote>
  
  <p>I tried to switch filtering and aggregation, tried doing <code>execute()</code> at the very end, but it does not help. How could this simple transformation be achieved - <code>filtering + aggregation</code>? I found examples of doing aggregations separately or filtering separately but have trouble finding both in one query.</p>