How to return documents from elasticsearch, based on the first element of array of strings?

Viewed 231

I have documents in elastic search as follows:

[
     {
       _index: myindex,
       name: John,
       hobbies: Swimming, Golfing
     },
     {
       _index: myindex,
       name: Alice,
       hobbies: Golfing, Swimming
     },
     {
       _index: myindex,
       name: Alice,
       hobbies: Golfing
     },
]

I need a way to return all the documents whose Hobbies are listed as first in the hobbies field.

I am using the elastic search NEST library to solve this problem. I've created a elasticsearch service, built with C# to create my queries. In this service I have a lookup for getting all the users and applying filters to the search. In this case I want to get all documents whose Hobbies are listed as Golfing first, if Golfing is not the first hobby then I don't want those documents.

Model:

public class User {
  public const string Name {get; set;}
  public List<string> Hobbies {get; set;}
}

My Query:

 query = query.Bool(b => b
    .Filter(filter => filter
      .Bool(b2 => b2
        .Must(must => must
          .Match(match => match
             .Field(l => l.Hobbies.First() == "Golfing")
            )
          )
       )

    )
);

I want to filter the documents, so that I only get the documents whose hobbies are first listed as Golfing. My expected result should be:

[
     {
       _index: myindex,
       name: Alice,
       hobbies: Golfing, Swimming
     },
     {
       _index: myindex,
       name: Alice,
       hobbies: Golfing
     },
]

However, it is returning all three. How do I make it so it only returns the documents, whose Hobbies have Golfing as the first hobby?

1 Answers

I think that the only way to achieve this is by using scrip query

In your case something like :

var response = client.Search(s => s
   .Query(q => q
       .Script(sq => sq
            .Source("doc['hobbies'].value[0]. == 'Golfing'")
            )
       )
   )
);
Related