Arun
Arun

Reputation: 1

Sub Queries in ElasticSearch

In elastic search i need all the documents whose userid's are a result from executing another elasticsearch query like this

{
"size": 200,
"query": {
    "bool": {
        "must": {
            "match": {
                "targetId": {
                    "query": 1234
                }
            }
        }
    }
},
"_source": {
    "includes": [
        "userId"
    ],
    "excludes": []
}
}

If executed in sql will have a query similar to the one down below.


select * from mytable where userId in (select userId from mytable where targetId = 1234);

But I'am unable to form a similar elasticsearch query, is there some other way of implementing sub queries in elasticsearch.

To elaborate the problem, i have added the data below

"hits": [
     {
        "_index": "idx0",
        "_type": "1234",
        "_id": "1235-1486716882293",
        "_source": {
           "targetid": "42644",
           "userid": "15784334830333693",
        }
     },
     {
        "_index": "idx0",
        "_type": "1234",
        "_id": "1235-1486716882293",
        "_source": {
           "data": {
              "info":"user data available"
           },
           "userid": "15784334830333693",
        }
     },
     {
        "_index": "idx0",
        "_type": "1234",
        "_id": "1235-1486716882293",
        "_source": {
           "data": {
              "info":"user data available"
           },
           "userid": "00000034830333693",
        }
     }
  ]

As u can see from the above data, user document has data that contains userid only, and the info of user who have achieved the target is stored in another document that has targetid and userid.

To find out the user who have achieved the targets, i need to execute two queries 1.get userids ES using targetid that i have, 2.get all documents that has userid from previous query.

Is there any other way to do it in a single query.

Upvotes: 0

Views: 2215

Answers (2)

core
core

Reputation: 871

Additional to the native ways there is the possibility to use the SIREn Join Plugin.

Upvotes: 0

NutcaseDeveloper
NutcaseDeveloper

Reputation: 191

Inner Joins are not allowed in ES. Coming from RDBMS world it is difficult to relate to but relationships are a trade-off for speed.

ES has various other ways of handling relationships which is discussed in detail here.

Upvotes: 1

Related Questions