How to get "related documents" in a query in Elasticearch?

615 views Asked by At

I have a problem in elasticsearch i am not being able to solve:

I have two different types in an index, one called 'keywords' and another one called 'products'. Keywords have the string property 'keyword_content', and products have the text property 'content'.

I need to query all the keywords with its first N related products each. The related relationship is defined by standard querying

I know I have the parent-child feature in ElasticSearch, but when I inserted the keywords i did not know the related products beforehand (the only way would be to, before inserting the keywords, use a search query on each keyword to know which products are related, and indexing the keywords with the correct products, but it would mean QUERYING EACH before inserting, which is costly).

Se let's assume I already have the two UNRELATED types in ElasticSearch. How do i query ALL the keywords with its associated N related products. I'm looking for a kind of 'dynamic field' that is the result of a query on a different type using as query string the 'keyword_content' property of each document.

I want something like:

Example of a keyword document:

{ "_id": 1,
  "keyword_content": "happy dogs"
}
{ "_id": 2, 
"keyword_content": "spaceship"
}

Example of product documents

{ "_id": "P1", "content": "This is a collar for happy dogs"}
{ "_id": "P2", "content": "This is a collar for angry dogs"}
{ "_id": "P3", "content": "This is a spaceship"}

I want something like this (i am simplifying the elasticsearch formats to better explain my usecase)(not that the types are NOT related, or maybe I can relate them, but i cannot specify which keyowrds are related to which product, i want elasticSearch to tell me that):

[
    {
         "_id": 1,
        "keyword_content": "happy dogs"
        "related_products": [
            { "_id": "P1", "content": "This is a collar for happy dogs"},
            { "_id": "P2", "content": "This is a collar for angry dogs"}
        ]
    },
    {
         "_id": 2,
        "keyword_content": "spaceship"
        "related_products": [
            { "_id": "P3", "content": "This is a spaceship"}
        ]
    }
]
0

There are 0 answers