Home > database >  elasticSearch count multiple
elasticSearch count multiple

Time:02-14

I have two profiles, "A" and "B" both have events in the elastic

this is the elastic data for ex:

 {hits: [
   {tag:"A"},
   {tag:"B"},
   {tag:B}
 ]}

I want to count how much events tag "a" have and and how much "B" in one request

Ive tried this but it counts them total as 3 and I want A:1 and B:2

GET forensics/_count
{
"query": {
 "terms": {
   "waas_tag": ["A","B"]
 }
}
}

CodePudding user response:

You can use term vector API to get information about the terms of a particular field.

Adding a working example with index data and response

Index Data

{
    "waas_tag": [
        {
            "tag": "A"
        },
        {
            "tag": "B"
        },
        {
            "tag": "B"
        }
    ]
}

Term Vector API:

GET _termvectors/1?fields=waas_tag.tag

Response:

"term_vectors": {
        "waas_tag.tag": {
            "field_statistics": {
                "sum_doc_freq": 2,
                "doc_count": 1,
                "sum_ttf": 3
            },
            "terms": {
                "a": {
                    "term_freq": 1,                           // note this
                    "tokens": [
                        {
                            "position": 0,
                            "start_offset": 0,
                            "end_offset": 1
                        }
                    ]
                },
                "b": {
                    "term_freq": 2,                           // note this
                    "tokens": [
                        {
                            "position": 101,
                            "start_offset": 2,
                            "end_offset": 3
                        },
                        {
                            "position": 202,
                            "start_offset": 4,
                            "end_offset": 5
                        }
                    ]
                }
            }
        }
    }

CodePudding user response:

at the end I found a solution not using count but msearch

GET forensics/_msearch
{} // this means {index:"forensics"}
{"query":{"term":{"waas_tag":"A"}}}
{} // this means {index:"forensics"}
{"query":
 {
 "bool":{
 "must":[{"term":{"waas_tag":"B"}
 },
 {
 "range":{"@timestamp":{"gte":"now-20d","lt":"now/s"}}}]}
 }
}

CodePudding user response:

You can use filters aggregation to get the count for each tag in a single query without using _msearch endpoint. This query should work:

{
  "size": 0,
  "aggs": {
    "counts": {
      "filters": {
        "filters": {
          "CountA": {
            "term": {
              "waas_tag": "A"
            }
          },
          "CountB": {
            "term": {
              "waas_tag": "B"
            }
          }
        }
      }
    }
  }
}
  • Related