# Query based on another query

**URL:** <https://discuss.elastic.co/t/query-based-on-another-query/50333>\
**Category:** Elasticsearch\
**Created:** [May 18, 2016, 12:23pm UTC](https://discuss.elastic.co/t/query-based-on-another-query/50333 "2016-05-18T12:23:03Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![diwertowski](https://avatars.discourse-cdn.com/v4/letter/d/ac91a4/32.png) [@diwertowski](https://discuss.elastic.co/u/diwertowski)\
**Post date:** [May 18, 2016, 12:23pm UTC](https://discuss.elastic.co/t/query-based-on-another-query/50333/1 "2016-05-18T12:23:03Z")

</div>

Is it possible to do something like this:

```
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "ID1": {
              "fields": ["ID1"],
              "query": {
                "bool": {
                  "must": [
                    {
                      "match": {
                        "ID2": 007
                      }
                  ...

```

It's somehting like this in SQL:

```
SELECT * FROM logstash-* w
WHERE w.ID1 IN ( SELECT o.ID1 FROM logstash-* o
                 WHERE o.ID2 = 007)

```

Is this possible?

- Hello world ID1=1234 ID2=007
- Hello world again ID1=1234
- Goodbye ID1=1234

It would be very nice, if I only have to type in ID2 and get all results which have the same ID1. All logfiles are in the same index, but it's no problem if the solution is, that we have to split them. I don't want to change any mappings or something like this, so parent/child doesn't work for me.

Any ideas? Is it possible?

---

<div class="post-metadata">

**Author:** ![TroyAndAbed](https://avatars.discourse-cdn.com/v4/letter/t/a8b319/32.png) [@TroyAndAbed](https://discuss.elastic.co/u/TroyAndAbed)\
**Post date:** [May 18, 2016, 12:56pm UTC](https://discuss.elastic.co/t/query-based-on-another-query/50333/2 "2016-05-18T12:56:14Z")

</div>

I'm not sure what you want but why don't you simply do:

> ```
> "query": {
> "bool": {
> "must":{
> "term": {
> "ID2" : "007"
> }
> }
> }
> }, "sort": "ID1"
> 
> ```

Or if you want all ID1 for the ID2 : 007:

```
 "query": {
    "bool": {
        "must":{
            "term": {
                "ID2" : "007"
            }
        }
    }
},
"size":0,
"aggs": {
    "groupy_by_ID1":{
        "terms": {
            "field":"ID1"
        }
    }
}

```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 10:50pm UTC](https://discuss.elastic.co/t/query-based-on-another-query/50333/3 "2017-07-05T22:50:41Z")

</div>


