gpt4 book ai didi

c# - 如何使用NEST(C#)在Elasticsearch中上传/索引GeoJson文件

转载 作者:行者123 更新时间:2023-12-03 01:22:40 25 4
gpt4 key购买 nike

我有GeoJson文件,我想通过NEST在Elastic Search上建立索引
但是由于缺乏专业知识,我在索引文档时遇到了麻烦
我创建了一个类,表示在ElasticSearch上的映射:

public class GeoDocument
{
[Nest.Keyword(Name = "DocId")]
public string DocId { get; set; }

[Nest.GeoShape(Name = "GeoField")]
public object GeoField { get; set; }
}

但是当我使用此映射为文档建立索引时

var polygon = "{\"type\":\"Polygon\",\"coordinates\":[[[5.856956,51.002753],[5.856928,51.002771],[5.856687,51.002853],[5.856956,51.002753]]]}";

var geoDocument = new GeoJson
{
DocId = "1",
GeoField = JsonConvert.DeserializeObject<object>(polygon)
};
var IndexResponse = client.IndexDocument(geoDocument);

我得到这样的结果
"_source": {
"DocId": "1",
"GeoField": [
[
[]
],
[
[
[
[
[],
[]
],
[
[],
[]
],
[
[],
[]
],
[
[],
[]
]
]
]
]
]
}
}

最佳答案

为了正确保存该JObject,您必须告诉ElasticClient使用NewtonSoft .Net序列化器。

  • 安装NEST.JsonNetSerializer软件包
  • 在ConnectionSettings中引用JsonNetSerializer
  • 如果更改设置后得到400,则可能需要创建一个新的索引。

  • 示例代码
    using Nest;
    using Elasticsearch.Net;
    using Nest.JsonNetSerializer;
        SingleNodeConnectionPool node = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    ConnectionSettings settings = new ConnectionSettings(
    node,
    JsonNetSerializer.Default
    );
    settings.DefaultMappingFor<GeoDocument>(m => m.IndexName("project2"));
    ElasticClient client = new ElasticClient(settings);

    // This is Supposed to be GeoDocument as per your question.
    GeoDocument geoDocument = new GeoDocument
    {
    DocId = "1",
    GeoField = JObject.Parse(polygon)
    // GeoField = JsonConvert.DeserializeObject<object>(polygon) // <-- Works too.
    };

    IndexResponse IndexResponse = client.IndexDocument(geoDocument);

    响应
    {
    "took": 1,
    "timed_out": false,
    "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
    },
    "hits": {
    "total": {
    "value": 1,
    "relation": "eq"
    },
    "max_score": 1.0,
    "hits": [
    {
    "_index": "project2",
    "_type": "_doc",
    "_id": "COQRXW8BNG2RJmIOyoO0",
    "_score": 1.0,
    "_source": {
    "DocId": "1",
    "GeoField": {
    "type": "Polygon",
    "coordinates": [
    [
    [
    5.856956,
    51.002753
    ],
    [
    5.856928,
    51.002771
    ],
    [
    5.856687,
    51.002853
    ],
    [
    5.856956,
    51.002753
    ]
    ]
    ]
    }
    }
    }
    ]
    }
    }

    关于c# - 如何使用NEST(C#)在Elasticsearch中上传/索引GeoJson文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59537992/

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