Azure SDK 正在开发全面的空间类型以跨服务共享。目前,需要一个单独的包来支持 Microsoft.Spatial。如果您使用 System.Text.Json(与“Azure.*”匹配的 Azure SDK 包的默认设置),请使用 https://www.nuget.org/packages/Microsoft.Azure.Core.Spatial/1.0.0-beta.1。如果您使用的是 Json.NET(即 Newtonsoft.Json),请使用 https://www.nuget.org/packages/Microsoft.Azure.Core.Spatial.NewtonsoftJson/1.0.0-beta.1。
查看https://github.com/Azure/azure-sdk-for-net/blob/Microsoft.Azure.Core.Spatial_1.0.0-beta.1/sdk/core/Microsoft.Azure.Core.Spatial.NewtonsoftJson/README.md 了解如何使用前者的示例,查看https://github.com/Azure/azure-sdk-for-net/blob/Microsoft.Azure.Core.Spatial.NewtonsoftJson_1.0.0-beta.1/sdk/core/Microsoft.Azure.Core.Spatial.NewtonsoftJson/README.md 了解后者。
您需要使用这些来生成您的 SearchIndex 并重新发布,以便空间 OData 过滤器能够正常工作。
对您发送的源进行一些修改(没有资源名称和 API 密钥 - 使用环境变量是个好主意,即使这些资源是临时的),您将使用如下内容:
Uri serviceEndpoint = new Uri($"https://{serviceName}.search.windows.net/");
var credential = new AzureKeyCredential(apiKey);
JsonSerializerOptions serializerOptions = new JsonSerializerOptions
{
Converters =
{
new MicrosoftSpatialGeoJsonConverter()
},
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
SearchClientOptions clientOptions = new SearchClientOptions
{
Serializer = new JsonObjectSerializer(serializerOptions)
};
var adminClient = new SearchIndexClient(serviceEndpoint, credential, clientOptions);
var searchClient = new SearchClient(serviceEndpoint, indexName, credential, clientOptions);
FieldBuilder fieldBuilder = new FieldBuilder
{
Serializer = clientOptions.Serializer
};
var definition = new SearchIndex(indexName)
{
Fields = fieldBuilder.Build(typeof(Sample))
};
adminClient.CreateOrUpdateIndex(definition);
IndexDocumentsBatch<Sample> batch = IndexDocumentsBatch.Create(
new IndexDocumentsAction<Sample>(IndexActionType.MergeOrUpload, new Sample { Id = "1", Location = GeographyPoint.Create(0, 0) }
));
try
{
IndexDocumentsResult result = searchClient.IndexDocuments(batch);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
// If for some reason any documents are dropped during indexing, you can compensate by delaying and
// retrying. This simple demo just logs the failed document keys and continues.
Console.WriteLine("Failed to index some of the documents: {0}");
}
Console.WriteLine("Hello World!");
还有你的模型:
public class Sample
{
[SimpleField(IsKey = true, IsFilterable = true, IsSortable = true)]
public string Id { get; set; }
[SimpleField(IsFilterable = true, IsSortable = true)]
public GeographyPoint Location { get; set; }
}
尽管您最初没有使用 FieldBuilder,但您为字段指定了 camelCase,但使用 PascalCase 声明了这些字段。请注意,Azure 认知搜索区分大小写,包括字段名称。