【问题标题】:Nest (Elasticsearch client for C#) Bulk IndexNest(C# 的 Elasticsearch 客户端)批量索引
【发布时间】:2016-02-11 02:08:47
【问题描述】:

ElasticSearch 的 Noob 和这里的 Nest。不完全确定我在这里做错了什么,但是这段代码抛出了

“格式错误的操作/元数据行 [1],应为 START_OBJECT 或 END_OBJECT,但找到了 [VALUE_NUMBER]”。

我知道 ES 抛出这个错误是因为 JSON is malformed。我不知道为什么 Nest 没有生成正确的 JSON?

注意:我希望能够进行批量索引操作,同时告诉它该有效负载应该转到哪个索引和类型。

public class Test
{
    private static Uri _node;
    private ElasticsearchClient _client;

    static Test()
    {
        _node = new Uri("http://localhost:9200");
    }

    public Test()
    {
        _client = new ElasticsearchClient(new ConnectionSettings(_node));
    }

    public void Bulk<T>(List<T> data, string index, string type) where T : class
    {
        _client.Bulk(index, type, data);
    }
}

【问题讨论】:

  • 你使用什么版本的 NEST 和 ES?您可以分享您尝试索引的类型吗?

标签: c# json elasticsearch nest


【解决方案1】:

当我认为您的意思是使用高级别 ElasticClient 时,您使用的是低级别 ElasticsearchClient。根据低级客户端的名称,我假设您使用的是 NEST 1.x,可能是最新版本 1.7.1。请注意,NEST 1.x 仅与 Elasticsearch 1.x 兼容,而 NEST 2.x 仅与 Elasticsearch 2.x 兼容。

要使用 NEST 1.x 批量索引,指定索引名称和类型名称将如下使用 fluent API

void Main()
{
    var settings = new ConnectionSettings(new Uri("http://localhost:9200"));

    // use NEST *ElasticClient*
    var client = new ElasticClient(settings, connection: new InMemoryConnection());

    var docs = new List<Doc>
    {
        new Doc(),
        new Doc(),
        new Doc(),
        new Doc(),
        new Doc()
    };

    var indexResponse = client.CreateIndex("docs", c => c
        .AddMapping<Doc>(m => m.MapFromAttributes())
    );

    var bulkResponse = client.Bulk(b => b
        .IndexMany(docs, (d, doc) => d.Document(doc).Index("index-name").Type("type-name"))
    );
}

public class Doc
{
    public Doc()
    {
        Id = Guid.NewGuid();
    }

    public Guid Id { get; set; }
}

【讨论】:

  • 是的,我在两天前使用的是最新的 NuGet。查看版本,我看到 Nest 是 1.0,Elasticsearch.Net 也是。我尝试了您的代码示例,但我在 Fiddler 中看到它,也没有看到在浏览器中运行 localhost:9200/_cat/indices?v 时创建的“index-name”索引。
  • 除非您在 Uri 中将 localhost 更改为 ipv4.fiddler,否则您不会看到它通过 fiddler。您可以更新您的问题以显示您正在使用的代码吗?我上面的示例使用InMemoryConnection 在内存中执行,因此实际上并没有发送到ES。从构造函数中删除InMemoryConnection,它将针对本地主机执行。
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 2020-12-22
  • 1970-01-01
  • 2023-03-30
  • 2015-02-19
  • 2012-09-23
  • 1970-01-01
  • 2016-04-16
相关资源
最近更新 更多