Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Elasticsearch.Net/NEST to search parent documents based on child attributes, where parent/child documents are stored separately

I would like to use Elasticsearch.Net/NEST to search related documents. For example, I have:

Person:

id name address_id
-- ---- ----------
1  John 1
2  Mary 2

Address:

id city
-- ------
1  Boston
2  Berlin

I'd like to store the Person and Address documents separately, and do queries where I return Person documents based on Address fields. For example, return all documents for people living in Boston. I've seen some examples in the Elaticsearch documentation using mapping and parent/child directives, but nothing for Elasticsearch.Net/NEST. Any code samples or pointers would be greatly appreciated...

like image 545
MiDu Avatar asked Jan 29 '26 22:01

MiDu


1 Answers

Here's a small snippet where the address is the parent

EDIT: Create the index:

var indicesOperationResponse = _client.CreateIndex(ci => ci.Index("test")
            .AddMapping<Address>(m => m.MapFromAttributes())
            .AddMapping<Person>(m => m.MapFromAttributes().SetParent<Address>()));

Index documents:

var bulkResponse = _client.Bulk(b => b
            .Index<Address>(bd => bd.Object(new Address { Name = "Tel Aviv", Id = 1 }).Index("test"))
            .Index<Person>(bd => bd.Index("test").Object(new Person {Id = 5, Address = 1, Name = "Me"}).Parent(1)));

And search by parent

var searchResponse = _client.Search<Person>(s => s
        .Query(q=>q.MatchAll())
        .Filter(q => q
            .HasParent<Address>(c => c
                .Query(cq => cq.Match(m=>m.OnField(t => t.Name).Query("Tel Aviv"))))));
like image 153
Udi Avatar answered Jan 31 '26 20:01

Udi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!