Amir Movahedi
Amir Movahedi

Reputation: 1792

Equal query in Elasticsearch by Nest client

public class User 
{
    public string Email { get; set; }
}

client.Index(new User { Email ="[email protected]" });

Query in Linq C# for example :

rep.Where(user=>user.Email=="[email protected]");

That works correctly.

I use same query in Nest:

client.Search<Post>(q => q
.Query(qu => qu
.Term(te=>te.OnField("email").Value("[email protected]"))));

Document result count is zero!!

But :

client.Search<Post>(q => q
.Query(qu => qu
.Term(te=>te.OnField("email").Value("test"))));

Document result count is 1 - why?

How I can make equal-query in ElasticSearch?

Upvotes: 0

Views: 2359

Answers (1)

Victor Suzdalev
Victor Suzdalev

Reputation: 2212

It's all because analyzers. Your document is parsed to terms while indexing, which means that elasticsearch stores something like an array of strings ["test", "test", "te"] in row with your document. Depending on what anayzer is configured (I guess it's standard one), you may get different terms decomposition. On the other side, your term request is not analyzed; that's why first request returns nothing - there's no such string as "[email protected]" in index strings ["test", "test", "te"], but there's a "test" string, so you get results for the second one. In your case you should use query_string query, but beware of the fact that such queries are analyzed too. It means, that if you index two documents, say {"Email":"[email protected]"} and {"Email":"[email protected]"}, without any flags query {"query":{"query_string":{"default_field":"Email","query":"[email protected]"}}} will return both documents because both of them contain "test" string in the index. To avoid this, use something like {"default_field":"Email","query":"[email protected]", "default_operator":"AND"}}} - default default operator is "OR".

Speaking of NEST, use query like

client.Search<Post>(q => q
    .Query(qu => qu
    .QueryString(qs=>qs
        .OnField(x=>x.Email).Query("[email protected]").Operator(Operator.and)
        )
    )
);

Upvotes: 2

Related Questions