向索引添加含特殊字符文档报错,.NET SDK如何设置allowUnsafeKeys?
解决Azure Cognitive Search无效文档键问题
一、在.NET SDK中设置allowUnsafeKeys
根据你使用的SDK版本不同,设置方式略有区别:
1. 新版Azure.Search.Documents SDK(推荐)
使用IndexDocumentsOptions类的AllowUnsafeKeys属性,在上传文档时传入配置:
var searchClient = new SearchClient( new Uri("你的搜索服务URI"), "你的索引名称", new AzureKeyCredential("你的API密钥") ); var options = new IndexDocumentsOptions { AllowUnsafeKeys = true }; // 假设documents是你要上传的文档集合 await searchClient.IndexDocumentsAsync(IndexDocumentsBatch.Upload(documents), options);
2. 旧版Microsoft.Azure.Search SDK
使用IndexDocumentsParameters类的AllowUnsafeKeys属性:
var indexClient = new SearchIndexClient( new Uri("你的搜索服务URI"), "你的索引名称", new SearchCredentials("你的API密钥") ); var parameters = new IndexDocumentsParameters { AllowUnsafeKeys = true }; await indexClient.Documents.IndexAsync(IndexDocumentsBatch.Upload(documents), parameters);
二、Base64编码后保留实际内容的方案
如果不想禁用安全键检查,可通过编码文档键+存储原键字段的方式解决:
- 对包含特殊字符的原始键进行URL安全的Base64编码,用编码后的字符串作为文档的
id(即文档键) - 在文档中新增一个字段(比如
originalKey),存储未编码的原始键内容
示例代码:
string originalKey = "TESTS123*14"; // 生成URL安全的Base64编码键 string encodedKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(originalKey)) .Replace('+', '-') .Replace('/', '_') .TrimEnd('='); // 构造文档,同时保留原键 var document = new { id = encodedKey, originalKey = originalKey, // 其他业务字段... }; // 上传文档(无需设置AllowUnsafeKeys) await searchClient.IndexDocumentsAsync(IndexDocumentsBatch.Upload(new[] { document }));
这样既符合搜索服务的键格式要求,又能在后续查询、检索时获取到原始的键内容。
内容的提问来源于stack exchange,提问作者Baski
相关产品推荐
相关产品推荐

