user1052610
user1052610

Reputation: 4719

NEST query for Elasticsearch not working

We are using the NEST API to work with Elasticsearch using C#. While we can insert data, queries which reference specific fields in an object are not working.

For example, given the following class:

internal class Magazine
{
   public Magazine(string id, string title, string author)
   {
      Id = id;
      Title = title;
      Author = author;
   }

   public string Id { get; set; }
   public string Title { get; set; }
   public string Author { get; set; }
}

Objects of the class are created and inserted into ElasticSearch as follows:

Magazine mag1= new Magazine("1", "Soccer Review", "John Smith");
Magazine mag2= new Magazine("2", "Cricket Review", "John Smith");

Uri node = new Uri("http://localhost:9200");
ConnectionSettings settings = new ConnectionSettings(node, defaultIndex: "mag-application");
ElasticClient client = new ElasticClient(settings);
client.Index(mag1);
client.Index(mag2);

The following query works, and returns two rows:

var searchResults = client.Search<Magazine>(s => s.From(0).Size(20));

But this one returns nothing:

var searchResults = client.Search<Magazine>(s => s.From(0).Size(20).Query(q => q.Term(p => p.Author, "John Smith")));

What is wrong?

Upvotes: 2

Views: 1615

Answers (1)

Manolis
Manolis

Reputation: 738

Since you are using the Standard analyzer (default option) the "John Smith" string is broken into 2 tokens "john" and "smith".

The term query :

Matches documents that have fields that contain a term (not analyzed).

That is to say, the phrase that you are searching for will not pass from the aforementioned analysis process.

Try searching

client.Search<Magazine>(s => s.From(0).Size(20).Query(q => q.Term(p => p.Author, "john")));

or use a Match query like the one below:

client.Search<Magazine>(s => s.From(0).Size(20)..Query(q => q.Match(m => m.OnField(p => p.Author).Query("John Smith"))

Check in the official documentation for term query for more information.

Upvotes: 5

Related Questions