2014-06-07 38 views
2

我正在過渡到我的網站上的ElasticSearch,並將NEST用作我的C#.NET接口。NEST - 各個字段的索引

在編寫索引我的內容的代碼中,我無法弄清楚如何單獨映射字段。假設我有以下幾點:

var person = new Person 
{ 
    Id = "1", 
    Firstname = "Martijn", 
    Lastname = "Laarman", 
    Email = "[email protected]", 
    Posts = "50", 
    YearsOfExperience = "26" 

}; 

而不是使用索引整個數據集:

var index = client.Index(person); 

我想要索引名和姓,使他們能夠在搜索,但我不需要其他字段將在索引中(ID除外),因爲它們只佔用空間。任何人都可以幫我用代碼來分別映射這些字段嗎?

回答

5

您應該在最初創建索引時添加映射。你可以做到這一點的方法之一是使用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部分。

+0

感謝您的幫助 - 文檔似乎已經爲新版本更新了一半。我需要然後調用以下行:client.Index(person,「person」,「string」,person.Id.ToString(),new IndexParameters {Refresh = true});添加數據集? – user1765523

+0

是的,上面的代碼只是創建您的索引並設置您的映射。你仍然需要索引你的文件。 –

+1

@GregMarzouka我認爲還沒有分析的指標仍然沒有分析?有第三個選項Index = FieldIndexOption.no。是否這是一個正確的關閉索引的屬性? – batmaci