I don't really understand this use case, but because it needs to run in two passes you have limited options:
- The only client-side way to run two passes in Kibana is using Canvas. You can make a request, and then script something to make another request
- In a batch process, you can set a field like
doc.hasMatching: truein documents and then use this in Kibana - You might be able to do this using a Continuous Transform