gpt4 book ai didi

c# - 使用 Elasticsearch NEST C# 索引 Json 文档

转载 作者:太空狗 更新时间:2023-10-29 23:05:56 26 4
gpt4 key购买 nike

我是 Elasticsearch 的新手,想知道如何使用 NEST C# 在 json 文档之后创建索引和索引到 Elasticsearch?

{
"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..."
}
]
}

最佳答案

用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,通过 .LowLevel 在 NEST 中可用。属性(property) 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")
)
)
);

这将返回索引的文档。泛型类型参数 dynamic用于 Search<T>()这里意味着生成的文档将被反序列化为 Json.Net JObject类型。

当我们创建索引时,我们没有为我们的类型指定映射,type-name ,因此 Elasticsearch 从 json 文档的结构中推断出映射。 This is dynamic mapping并且在许多情况下都很有用,但是,如果您知道要发送的文档的结构并且不会对其进行破坏性更改,那么您 specify a mapping for the type .在这个特定示例中这样做的好处是 chapter数组将被推断为 object type映射,但如果您想搜索单个章节的章节名称和章节描述,那么您可能想要映射 chapter作为 nested type .

关于c# - 使用 Elasticsearch NEST C# 索引 Json 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37819542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com