简体   繁体   中英

NEST - Index individual fields

I'm transitioning to ElasticSearch on my website and am using NEST as my C# .NET interface.

In writing code to index my content, I can't figure out how to map fields individually. Suppose I have the following:

var person = new Person
{
    Id = "1",
    Firstname = "Martijn",
    Lastname = "Laarman",
    Email = "Martijn@gmail.com",
    Posts = "50",
    YearsOfExperience = "26"

};

Rather than indexing the entire dataset using:

var index = client.Index(person);

I want to index FirstName and LastName so that they can be searched upon, but I don't need the other fields to be in the index (other than ID) because they would only take up space. Can anyone help me with the code to map these fields individually?

You should add a mapping when you create your index initially. One way you can do this is with using NEST attributes on your class like this:

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; }
}

Then you would create your index like this:

client.CreateIndex("person", c => c.AddMapping<Person>(m => m.MapFromAttributes()));

Instead of using attributes, you could also explicitly map each field:

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)))));

Check out the NEST documentation for more info, specifically Create Index and Put Mapping sections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM