Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a "join"/"sub-query" using ElasticSearch?

I'm new to ElasticSearch, and I would like to able to do a query against an index, which then uses a part of the result to do another query.

For example, we have a tags index which we can query for a matching tag. That index contains stored fields identifying the content it's associated with (hooked to). Each type of content has it's own index. I need to be able to query for a tag match, and have it return not only the tag result, but a stored field (in this case title) from the content which it is associated with (different index).

like image 933
Spot Avatar asked Nov 26 '13 23:11

Spot


People also ask

Can you do joins in Elasticsearch?

Out of the box, Elasticsearch does not have joins as in an SQL database. While there are potential workarounds for establishing relationships in your documents, it is important to be aware of the challenges each of these approaches presents.

How do I merge two queries in Elasticsearch?

You need to use the bool query to combine different queries together. You can then choose whether each single query must match, should match (optional), or must not match.

How do you write nested query in Elasticsearch?

You can perform a nested query in Elasticsearch by using the nested parameter. A nested query will search the nested field objects and return the document's root parent if there's a matching object.


1 Answers

I faced with the similar problem. You need a join here. Elasticsearch Team advises to use application side. ES emulates a relational database by implementing joins in our application: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/application-joins.html So you can use any of the ES client and write something similar

    SearchResponse response = client.prepareSearch(scriptVersionFirst)
                   .setTypes("yourtype")
                   .setQuery(QueryBuilders.termQuery("multi", "test"))
                   .setFrom(0).setSize(60).setExplain(true)
                   .execute()
                   .actionGet();

    if (response != null) {
        SearchHits hitList = response.getHits();
        if (hitList != null) {
            SearchHit[] hits = hitList.hits();          
            for (SearchHit hit : hits) 
                MethodPojo source = gson.fromJson(hit.getSourceAsString(), MethodPojo.class);
                System.out.println("Found: " + getMethodResultEntity(scriptVersionSecond, hit.getType(), source.getMethodName(), source.getMethodDesc(), source.getRequest()));
            }
        }

Here function getMethodResultEntity return result of other get query.

P.S. Im using here ES java client. It's a little bit heavy. If you need java client it's better to use jest client - much light version for simple situation.

like image 102
Iana Mykhailenko Avatar answered Nov 06 '22 19:11

Iana Mykhailenko