Calculate counts of hits of several subqueries inside one query to Elasticsearch
<p>I have 3 fields in a document that I need to match. I'd like to identify which of those 3 fields have any matches.</p>

<p>More specifically, I'd like to find out if the given wildcard query matches only one field through the document set or matches several fields. If the wildcard query matches only, say <code>field1</code>, then I can make a conclusion that the given wildcard query is applicable to only <code>field1</code>. If the wildcard query matches two or three fields, then I cannot make such a conclusion and I'll wait for more characters to be entered by user to narrow search.</p>

<p>I've written the following query that matches all 3 fields:</p>

<pre><code>{
  "query": {
    "bool": {
      "should": [
        {"wildcard": { "field1": "*R*" }},
        {"wildcard": { "field2": "*R*" }},
        {"wildcard": { "field3": "*R*" }}
      ]
    }
  },
  "size": 0
}
</code></pre>

<p>It returns the total count of all documents that have matches on any of those fields. Now I'd like to know if it's possible to receive 3 separate counts for each subquery. This can be achieved by sending 3 separate requests but I'd like to minimize the number of requests to elasticsearch.</p>

<p>I've tried <code>bool</code> and <code>dis_max</code> queries but could not find a solution.</p>

<h1>UPDATE</h1>

<p>Using <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-named-queries-and-filters.html" rel="nofollow">named queries</a> I've built the following query:</p>

<pre><code>{
  "query": {
    "bool": {
      "should": [
        {"wildcard": { "field1": { "value": "*R*", "_name": "query1" }}},
        {"wildcard": { "field2": { "value": "*R*", "_name": "query2" }}},
        {"wildcard": { "field3": { "value": "*R*", "_name": "query3" }}}
      ]
    }
  },
  "size": 1
}
</code></pre>

<p>This query returns a single result with the best score. By default, the score is higher when more fields are matched in the same document. So if the found document was matched by two or three fields, it already answers my initial question. However, if the found document was matched by a single field, say, <code>field1</code>, it does not guarantee there are no other documents that are matched by <code>field2</code> or <code>field3</code>, so it's still not a solution.</p>

<p>Do I have to send 3 requests to run searches over each field separately to solve my problem?</p>