Michael
Michael

Reputation: 557

ElasticSearch with NEST query issue

Forgive my newbish-ness as I am new to both ElasticSearch and NEST. I am working on a prototype to evaluate ElasticSearch in a .NET solution being implemented. The prototype compiles and does seem to search, but isn't properly returning results. It only returns results on a few keywords, lowercase only, while ignoring others and returning nothing. I am thinking there's something wrong in my query. Here's the query part (assume connection info and default index specified and built).

// string searchString to be searched against ProductName and Description fields.            
var searchResults = client.Search<Product>(s=>s
            .From(0)
            .Size(100)
            .Query(q=>q.Term(p=>p.ProductName, searchString) || 
                q.Term(p=>p.Description, searchString)
            ));

Here's the model if needed:

[ElasticType(IdProperty = "ProductID")]
public class Product
{
    [ScaffoldColumn(false)]
    [JsonIgnore]
    public int ProductID { get; set; }

    [Required, StringLength(100), Display(Name = "Name")]
    public string ProductName { get; set; }

    [Required, StringLength(10000), Display(Name = "Product Description"), DataType(DataType.MultilineText)]
    public string Description { get; set; }

    public string ImagePath { get; set; }

    [Display(Name = "Price")]
    public double? UnitPrice { get; set; }

    public int? CategoryID { get; set; }
    [JsonIgnore]
    public virtual Category Category { get; set; }
}

Appreciate the help!

Upvotes: 0

Views: 1570

Answers (1)

Greg Marzouka
Greg Marzouka

Reputation: 3325

Your issue here is that you're using term queries, which are not analyzed and thus are case-sensitive.

Try using a match query (which is analyzed) instead:

var searchResults = client.Search<Product>(s => s
    .From(0)
    .Size(100)
    .Query(q => 
        q.Match(m => m.OnField(p => p.ProductName).Query(searchString)) || 
        q.Match(m => m.OnField(p => p.Description).Query(searchString))
     )
);

Taking it one step further- since you are querying the same text on two different fields, you can use a multi match query instead of combining the two term queries:

var searchResults = client.Search<Product>(s => s
    .From(0)
    .Size(100)
    .Query(q => q
        .MultiMatch(m => m
            .OnFields(p => p.Product, p => p.Description)
            .Query(searchText)
        )
     )
);

For a better understanding of analysis, the mapping and analysis section from The Definitive Guide is a great read.

Upvotes: 2

Related Questions