var local = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(local, null);
var elastic = new ElasticClient(settings);
var res = elastic.CreateIndex(ci => ci
.Index("my_first_index_final2")
.AddMapping<BlogPost>(m => m.MapFromAttributes()));
Console.WriteLine(res.RequestInformation.Success);
var blogPost = new BlogPost
{
Id = Guid.NewGuid(),
Title = "First blog post",
Body = "This is very long blog post!"
};
var firstId = blogPost.Id;
var result = elastic.Index(blogPost, p => p
.Index("my_first_index_final2")
.Id(blogPost.Id.ToString())
.Refresh());
Console.WriteLine(result.RequestInformation.Success);
Blogpost类:
[ElasticType(IdProperty = "Id", Name = "blog_post")]
public class BlogPost
{
[ElasticProperty(Name = "_id", Index = FieldIndexOption.NotAnalyzed, Type = FieldType.String)]
public Guid? Id { get; set; }
[ElasticProperty(Name = "title", Index = FieldIndexOption.Analyzed, Type = FieldType.String)]
public string Title { get; set; }
[ElasticProperty(Name = "body", Index = FieldIndexOption.Analyzed, Type = FieldType.String)]
public string Body { get; set; }
public override string ToString()
{
return string.Format("Id: '{0}', Title: '{1}', Body: '{2}'", Id, Title, Body);
}
}
这是我的代码。每次返回:
真正
假
意思是,它创建索引,但是无法将文档插入索引。我不明白原因。
另外,我每次运行此演示控制台应用程序时都必须重命名索引名称,因为我认为我们无法插入具有相同名称的索引。我如何避免这样做?
我正在关注本教程:
https://www.devbridge.com/articles/getting-started-with-elastic-using-net-nest-library-part-two/
任何其他学习嵌套和 flex 搜索的资源,请随时提出建议。
最佳答案
我的猜测是您正在使用Elasticsearch2.x。您的代码在Elasticsearch 1.x中不会中断。问题是,您正在尝试在文档中添加字段_id
。它是元数据字段之一,Elasticsearch 2.x禁止您在文档内部对其进行索引。为了使您的代码正常工作,只需将Id
字段的名称从_id
更改为其他名称,例如id
。