# How to aggregate on bitwise operator individual flag values?

We have cities where each has some sporting places, and some places are present in multiple cities:

London: Multiplex, Fivestar
Berlin: Multiplex, Bestgym
Paris: Multiplex, Bestgym, Fivestar

We have places where each place has some content to offer. For example:

Bestgym: gym, bar
Fivestar: water pool, bar
Multiplex: gym, bar, football, table tennis

In the field contents we store an integer which represents a combination of different flags which we resolve with a bitwise operator (a good read on this approach here: How we built a reversible recommendation system using Elasticsearch). For example:

1: gym
2: bar
4: football
8: table tennis
16: water pool

Following this logic, on document level for each place we store a number:

placeA: 3 (1+2)
placeB: 18 (16+2)
placeC: 15 (1+2+4+8)

Using bitwise operaton we can easily resolve which contents each place has. We can even easily filter out which cities have a certain content. For example, if we wanted all places in a specific city which contain gym, bar and football (1+2+4=7), it would look like this:

"query": {
"constant_score": {
"filter": {
"bool": {
"must": [
{
"match": {
"city": "London"
}
},
{
"script": {
"script": {
"lang": "expression",
"source": "7 & doc['contents'].value"
}
}
}
]
}
}
}
}

The Problem:
We want to get all contents a city has to offer. If I were to do a simple aggregation on top of the upper query, it would return all possible permutations of flag sums, e.g.:
1,2,3,7,14,15,18,28,31

What I want is, get bucket results which represent the flag number of the contents, e.g.
2,4,16

Any ideas how this would be achievable?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.