我有一个网络应用程序API,它使用ACS V11 SDK来搜索索引文档并返回搜索结果。下面是我的 API 接口中的简化代码:
public async Task<SearchResults<SearchDocument>> SearchIndexDocumentsAsync(
[FromBody] SearchParameters parameters,
CancellationToken cancellationToken = default)
{
var searchIndexClient = new SearchIndexClient(
new Uri(endpoint),
new AzureKeyCredential(apiKey));
var searchClient = searchIndexClient.GetSearchClient(indexName);
SearchResults<SearchDocument> docs = await searchClient.SearchAsync<SearchDocument>(parameters.Query, searchOptions: null, cancellationToken).ConfigureAwait(false);
return docs;
}
问题是,响应Json只包含总数,但没有文档结果,如下所示:
{
"totalCount": 19
}
我知道我可以迭代 ACS SDK 响应中的所有文档并将它们添加到如下列表中:
var results = new List<SearchResult<SearchDocument>>();
await foreach (SearchResult<SearchDocument> document in docs.GetResultsAsync())
{
results.Add(document);
}
return results;
但是有没有更简单的方法来返回包括文档的完整搜索结果,而不必迭代所有文档?
一种可能的方法是返回
Response<SearchResults<SearchDocument>>
而不是返回 SearchResults<SearchDocument>
。
这样,您将返回整个响应对象,其中包括搜索结果。
我在下面的代码片段中使用了它:
static async Task Main(string[] args)
{
var searchIndexClient = new SearchIndexClient(
new Uri(endpoint),
new AzureKeyCredential(apiKey));
var searchClient = searchIndexClient.GetSearchClient(indexName);
string query = "Sample";
Response<SearchResults<SearchDocument>> response = await searchClient.SearchAsync<SearchDocument>(query);
string jsonResponse = JsonConvert.SerializeObject(response.Value.GetResults(), Formatting.Indented);
Console.WriteLine(jsonResponse);
通过上面的代码片段,我可以获得所有结果文档。