我正在网站上过渡到 ElasticSearch,并使用 NEST 作为我的 C# .NET 接口(interface)。
在编写代码来索引我的内容时,我无法弄清楚如何单独映射字段。假设我有以下内容:
var person = new Person
{
Id = "1",
Firstname = "Martijn",
Lastname = "Laarman",
Email = "Martijn@gmail.com",
Posts = "50",
YearsOfExperience = "26"
};
而不是使用以下方式索引整个数据集:
var index = client.Index(person);
我想对 FirstName 和 LastName 建立索引,以便可以搜索它们,但我不需要索引中包含其他字段(ID 除外),因为它们只会占用空间。谁能帮我编写代码来单独映射这些字段?
最佳答案
您应该在最初创建索引时添加映射。实现此目的的一种方法是在类上使用 NEST 属性,如下所示:
public class Person
{
public string Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
[ElasticProperty(Store=false, Index=FieldIndexOption.not_analyzed)]
public string Email { get; set; }
[ElasticProperty(Store = false, Index = FieldIndexOption.not_analyzed)]
public string Posts { get; set; }
[ElasticProperty(Store = false, Index = FieldIndexOption.not_analyzed)]
public string YearsOfExperience { get; set; }
}
然后您将像这样创建索引:
client.CreateIndex("person", c => c.AddMapping<Person>(m => m.MapFromAttributes()));
您还可以显式映射每个字段,而不是使用属性:
client.CreateIndex("person", c => c.AddMapping<Person>(m => m
.MapFromAttributes()
.Properties(props => props
.String(s => s.Name(p => p.Email).Index(FieldIndexOption.not_analyzed).Store(false))
.String(s => s.Name(p => p.Posts).Index(FieldIndexOption.not_analyzed).Store(false))
.String(s => s.Name(p => p.YearsOfExperience).Index(FieldIndexOption.not_analyzed).Store(false)))));
查看 NEST documentation欲了解更多信息,特别是 Create Index和 Put Mapping部分。
关于c# - NEST - 索引各个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24100965/