NEST - 索引单个字段

时间:2014-06-07 19:46:23

标签: c# elasticsearch nest

我正在我的网站上转换到ElasticSearch,并使用NEST作为我的C#.NET界面。

在编写代码来索引我的内容时,我无法弄清楚如何单独映射字段。假设我有以下内容:

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除外)因为它们只占用空间。任何人都可以帮助我使用代码来单独映射这些字段吗?

1 个答案:

答案 0 :(得分:6)

您应该在最初创建索引时添加映射。一种方法是在类上使用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 IndexPut Mapping部分。