2016-06-14 39 views
5

我對Elasticsearch很新穎,想知道如何使用NEST C#將以下json文檔的索引和索引創建爲Elasticsearch?使用Elasticsearch NEST的索引Json文檔C#

{ 
    "BookName": "Book1", 
    "ISBN": "978-3-16-148410-0", 
    "chapter" : [ 
     { 
      "chapter_name": "Chapter1", 
      "chapter_desc": "Before getting into computer programming, let us first understand computer programs and what they..." 
     }, 
     { 
      "chapter_name": "Chapter2", 
      "chapter_desc": "Today computer programs are being used in almost every field, household, agriculture, medical, entertainment, defense.." 
     }, 
     { 
      "chapter_name": "Chapter3", 
      "chapter_desc": "MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are..." 
     }, 
     { 
      "chapter_name": "Chapter4", 
      "chapter_desc": "Computer programs are being used to develop graphics and special effects in movie..." 
     } 
    ] 
} 
+0

https://github.com/elastic/elasticsearch-net/issues/336 –

回答

5

要創建具有NEST索引很簡單,只要

var client = new ElasticClient(); 
client.CreateIndex("index-name"); 

這將創建與節點定義碎片和副本的默認數量的指標。

索引表示爲JSON入索引的文檔將

var json = @"{ 
    ""BookName"": ""Book1"", 
    ""ISBN"": ""978-3-16-148410-0"", 
    ""chapter"" : [ 
     { 
      ""chapter_name"": ""Chapter1"", 
      ""chapter_desc"": ""Before getting into computer programming, let us first understand computer programs and what they..."" 
     }, 
     { 
    ""chapter_name"": ""Chapter2"", 
      ""chapter_desc"": ""Today computer programs are being used in almost every field, household, agriculture, medical, entertainment, defense.."" 
     }, 
     { 
    ""chapter_name"": ""Chapter3"", 
      ""chapter_desc"": ""MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are..."" 
     }, 
     { 
    ""chapter_name"": ""Chapter4"", 
      ""chapter_desc"": ""Computer programs are being used to develop graphics and special effects in movie..."" 
     } 
    ] 
}"; 

var indexResponse = client.LowLevel.Index<string>("index-name", "type-name", json); 

if (!indexResponse.Success) 
    Console.WriteLine(indexResponse.DebugInformation); 

這裏我們使用低等級客戶機索引JSON,可在NEST通過.LowLevel財產上ElasticClient

要搜索索引文件將

// refresh the index so that newly indexed documents are available 
// for search without waiting for the refresh interval 
client.Refresh("index-name"); 

var searchResponse = client.Search<dynamic>(s => s 
    .Index("index-name") 
    .Type("type-name") 
    .Query(q => q 
     .Match(m => m 
      .Query("Photoshop") 
      .Field("chapter.chapter_desc") 
     ) 
    ) 
); 

這將返回索引的文檔。這裏使用的Search<T>()中使用的泛型類型參數dynamic表示生成的文檔將被反序列化爲Json.Net JObject類型。

當我們創建索引時,我們沒有爲我們的類型type-name指定映射,因此Elasticsearch從json文檔的結構推斷出映射。 This is dynamic mapping,並且可以用於許多情況,但是,如果您知道要發送的文檔的結構並且不會被破壞性更改,那麼您可以使用specify a mapping for the type。在這個特定的例子中這樣做的好處是chapter數組將被推斷爲object type映射,但是如果您想跨個別章節的章節名稱和章節描述進行搜索,那麼您可能想要將chapter映射爲nested type

相關問題