【问题标题】:search via a Term query using NEST client for elastic search使用 NEST 客户端通过 Term 查询进行弹性搜索
【发布时间】:2014-01-15 17:24:05
【问题描述】:

我很难按特定术语搜索文档。每次我都得到零结果。

这是一个代码示例:

var customers = new List<SampleCustomer>();
customers.Add(new SampleCustomer(){id=1,firstname="John", surname="Smith", country = "UK", sex = "Male", age=30});
customers.Add(new SampleCustomer(){id=2,firstname="Steve", surname="Jones",  country ="UK", sex = "Male", age=22});
customers.Add(new SampleCustomer(){id=3,firstname="Kate", surname="Smith",  country ="UK", sex = "Female", age=50});
customers.Add(new SampleCustomer(){id=4,firstname="Mark", surname="Jones",  country ="USA", sex = "Male", age=45});
customers.Add(new SampleCustomer(){id=5,firstname="Emma", surname="Jonson",  country ="USA", sex = "Female", age=25});
customers.Add(new SampleCustomer(){id=6,firstname="Tom", surname="Jones",  country ="France", sex = "Male", age=30});
customers.Add(new SampleCustomer(){id=7,firstname="Liz", surname="Web",  country ="France", sex = "Female", age=45});

foreach (var customer in customers)
{
    _elasticClient.DeleteById("sample", "SampleCustomers",customer.id);
    _elasticClient.Index(customer, "sample", "SampleCustomers" , customer.id);
}

使用此索引,我可以使用查询字符串过滤器查询名字为 smith 的客户

var queryByQueryString = _elasticClient.Search<SampleCustomer>(s =>
           s.From(0).Size(10).Type("SampleCustomers")
           .Query(q => q.QueryString(qs => qs.Query("Smith").OnField("surname"))));

但如果我尝试使用术语文件管理器搜索客户,我得到的结果为零

var queryByTerm = _elasticClient.Search<SampleCustomer>(s =>
            s.From(0).Size(10).Type("SampleCustomers")
            .Query(q => q.Term(p => p.surname, "Smith")));

我不知道我做错了什么?在上面的示例中,我想确保我的查询只返回姓氏完全等于“Smith”的结果,并且如果某人有一个双管姓氏,例如“Smith Jones”,他们就不会出现在结果中。

【问题讨论】:

    标签: elasticsearch nest


    【解决方案1】:

    如果没有看到您的映射,很难确定,但您的问题可能只是区分大小写。如果"surname" 字段使用默认的standard analyzer(除非您在映射中指定一个),则标记将被修改为小写。所以会有一个"smith" 令牌但没有"Smith"。当您使用查询字符串查询时,您的查询文本将被分析(使用 standard 分析器,除非您提供),因此搜索文本被修改为与标记匹配的 "smith"。但是term filter 不做任何分析,过滤文本"Smith" 不匹配任何标记,因此不返回任何结果。

    如果这确实是您的问题,那么这应该返回结果:

    var queryByTerm = _elasticClient.Search<SampleCustomer>(s =>
                s.From(0).Size(10).Type("SampleCustomers")
                .Query(q => q.Term(p => p.surname, "smith")));
    

    或者,您可以在映射中将 "surname" 字段设置为 "index": "not_analyzed"(需要重新索引),因此标记不会小写,并且您的术语过滤器将使用文本 "Smith"匹配。

    【讨论】:

    • 谢谢,是的,小写字母有效。我不能让它与史密斯一起工作。我确实将 not_analysed 属性添加到 Sample customer 类的 surname 属性中,但它没有改变任何东西。例如[ElasticProperty(Index = FieldIndexOption.not_analyzed)] public string surname { get;放; }
    • 您是否使用新映射重新索引?你确定它有效吗?能发一下映射吗?不看映射很难知道出了什么问题。我对 Nest 不太熟悉,但您只需点击 http://[endpoint]/[index_name]/_mapping 即可获取映射
    猜你喜欢
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多