c# - 使用特殊字符时,Azure 搜索 SDK 无法进行部分搜索

标签 c# azure lucene azure-cognitive-search azure-search-.net-sdk

我有一个下面的代码,它应该从 azure 索引返回所有以 T&S 开头的名称 例如结果应该如下所示

  • 条款与条件
  • T&S 有限公司
  • T&S 公司

我们在代码中看到的搜索文本是“T&S*”的 UrlEncoded 版本

搜索代码块

   var response = await _searchClient.Documents.SearchAsync<customDto>("%22T%26S%22*",
            new SearchParameters
            {
                SearchFields = new List<string> { "Name" },
                SearchMode = SearchMode.All
            });

自定义DTO

   public class CustomDto{
          public CustomDto(int id,string name)
          {
             Id=Convert.ToString(id),
             Name=name
          }

          [IsSearchable, IsFilterable]
          [System.ComponentModel.DataAnnotations.Key]
          public string Id { get; }

          [IsSearchable, IsFilterable, IsSortable]
          public string Name {get;}

   }

现在, 如果我将类似的搜索文本放在 azure 搜索查询窗口上 我得到了预期的结果 %22T%26S%22*&searchMode=all&searchFields=Name

但由于某种原因,代码返回空结果。我不明白我在这里做错了什么。

请帮忙。

谢谢

最佳答案

您可以尝试使用以下代码吗?这使用 Microsoft.Azure.Search SDK(版本 10.1.0)。

        var searchCredentials = new SearchCredentials("<api-key (admin or query>");
        var indexClient = new SearchIndexClient("<search-service-name>", "<index-name>", searchCredentials);
        var results = indexClient.Documents.Search("\"T\\&S\"*",
        new SearchParameters
        {
            SearchFields = new List<string> { "Name" },
            SearchMode = SearchMode.All
        });

SDK 实际上会发出一个 POST 请求,因此您实际上不必对搜索字符串进行 URL 编码(当您发出 GET 请求时,您需要这样做) 。您需要做的是通过在 & 字符前加上 \ 前缀来转义 & 字符,这就是我所做的。请参阅此处的转义特殊字符:https://learn.microsoft.com/en-us/azure/search/query-lucene-syntax#bkmk_syntax了解更多信息。

关于c# - 使用特殊字符时,Azure 搜索 SDK 无法进行部分搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62213272/

相关文章:

c# - 使用 .NET 从 FileStream 的特定位置读取数据

c# - 字符串的双引号问题

java - 使用的 Lucene 搜索库算法

Java Lucene NRT 搜索不工作

elasticsearch - 在ElasticSearch中不带映射的带斜杠的值的术语过滤器

c# - 哪些 .Net 程序集作为标准集成到 SQL Server 2008 R2 CLR 中?

c# - 在 SQL 命令上将相等性更改为其他内容

node.js - 使用 docker 镜像的 Azure Linux 应用服务中的 Mongo 连接错误

Azure 容器注册表权限

azure - Azure Devops YAML 管道中的手动触发阶段