How to search nested Doc in Elasticsearch_dsl

314 Views Asked by At

I have multiple indices on of them called Post with Nested document Comment.

this is how my documents defined

class CommentDoc(InnerDoc):
    title = Text(analyzer=ngram_analyzer)
    content = Text(analyzer=ngram_analyzer)
class PostDoc(Document):
    content = Text(analyzer=ngram_analyzer)
    comments = Nested(Icd10Doc)
    id = Integer()

this is how I'm doing the current search

s = Search(index=['post', 'blog', 'artical'])
q = Q("multi_match", query="whatever", fields=['name', 'title', 'content'])
s = s.query(q)

So how can I search the Post index using the nested Docs inside comments?

what should I add to fields array?

1

There are 1 best solutions below

0
On

At first I think you should edit your models but I'm not sure:

comments = Nested(Icd10Doc) ---> comments = Nested(CommentDoc)

I had tested this query at similiar conditions and I think its works for you

nested_q = Q("nested", path='comments', query=Q("multi_match", query="whatever", fields=['comments.content']))

And finally if you want to combine queries you can use this:

final_q = nested_q & other_q (for AND operation)

final_q = nested_q | other_q (for OR operation)

And finally:

s = s.query(final_q)