Skip to content

Instantly share code, notes, and snippets.

@beachside-project
Last active August 2, 2023 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beachside-project/58789af9819a67872f39f18188c4dbf3 to your computer and use it in GitHub Desktop.
Save beachside-project/58789af9819a67872f39f18188c4dbf3 to your computer and use it in GitHub Desktop.
Cognitive Search client factory sample
using Azure;
using Azure.Core.Serialization;
using Azure.Search.Documents;
using Azure.Search.Documents.Indexes;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Text.Json;
namespace SerializerCustomizeSamples
{
public class SearchClientFactory
{
public static SearchClient Create(CognitiveSearchOptions options)
{
var credential = new AzureKeyCredential(options.AdminApiKey);
var searchIndexClient = new SearchIndexClient(options.SearchEndpointUri, credential);
return searchIndexClient.GetSearchClient(options.IndexName);
}
/// <summary>
/// Newtonsoft の CamelCase の Serializer をセットした SearchClient を生成
/// </summary>
/// <returns></returns>
/// <remarks>
/// このメソッドを使うには以下の NuGet が必要:
/// - Microsoft.Azure.Core.NewtonsoftJson for "NewtonsoftJsonObjectSerializer"
/// </remarks>
public static SearchClient CreateWithNewtonSoftSerializer(CognitiveSearchOptions options)
{
var jsonSerializerSettings = NewtonsoftJsonObjectSerializer.CreateJsonSerializerSettings();
jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// 必要に応じて Converter を追加。
// jsonSerializerSettings.Converters.Add(new StringEnumConverter());
var searchClientOptions = new SearchClientOptions { Serializer = new NewtonsoftJsonObjectSerializer(jsonSerializerSettings) };
var credential = new AzureKeyCredential(options.AdminApiKey);
return new SearchClient(options.SearchEndpointUri, options.IndexName, credential, searchClientOptions);
}
/// <summary>
/// System.Text.Json の CamelCase の Serializer をセットした SearchClient を生成
/// </summary>
/// <returns></returns>
public static SearchClient CreateWithSystemTextJsonSerializer(CognitiveSearchOptions options)
{
var jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var searchClientOptions = new SearchClientOptions { Serializer = new JsonObjectSerializer(jsonSerializerOptions) };
var credential = new AzureKeyCredential(options.AdminApiKey);
return new SearchClient(options.SearchEndpointUri, options.IndexName, credential, searchClientOptions);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment