You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用@azure/search-documents在Next.js中实现Azure语义搜索?

在Next.js中用@azure/search-documents实现Azure认知搜索语义检索

核心问题解决思路

你遇到的queryType: "semantic"不在azure-search-types的QueryType枚举里,是因为该枚举未包含语义检索类型。实际上可以直接用字符串字面量"semantic"指定,同时需确保API版本支持(你使用的2023-11-01完全符合要求),并补充语义检索必需的配置参数。

修改后的完整代码

import { IError } from "@/app/_lib/ts/types/error";
import { AzureKeyCredential, SearchClient, SearchOptions } from "@azure/search-documents";
import { SearchMode } from "azure-search-types";
import { NextRequest, NextResponse } from "next/server";

export interface AzureCognitiveSearchResult {
  score: number;
  document: any; // 根据实际文档结构调整类型
}

// 语义搜索配置:直接用字符串指定queryType,添加语义配置参数
const searchConfig: SearchOptions = {
  top: 2,
  searchMode: SearchMode.any,
  queryType: "semantic" as const, // 用as const让TypeScript识别为合法值
  semanticConfigurationName: "你的语义配置名称", // 替换为Azure索引中配置的语义名称
  queryLanguage: "zh-cn", // 根据文档语言设置,英文用"en-us"
  // 可选:开启提取式问答/标题,需索引配置支持
  queryAnswer: "extractive",
  queryCaption: "extractive"
};

const defaultMinScore = '1.0'; // 语义得分范围通常为0-4,需调整阈值

export interface AzureCognitiveSearchResponse {
  query: {
    _id: string,
    input: string,
    results: AzureCognitiveSearchResult[]
  }
} 

export async function POST(req: NextRequest): Promise<NextResponse> {
  let searchResults: AzureCognitiveSearchResponse[] = [];
  const serviceName = process.env.AZURE_COGNITIVE_SEARCH_SERVICENAME;
  const indexName = process.env.AZURE_COGNITIVE_SEARCH_INDEXNAME;
  const adminKey = process.env.AZURE_COGNITIVE_SEARCH_QUERYKEY;
  const endpoint = `https://${serviceName}.search.windows.net`;

  const { data, minScore } = await req.json();

  if (!data) {
    return NextResponse.json({ message: "未向认知搜索API传递数据" }, { status: 400 });
  }

  try {
    const searchClient = new SearchClient(
      endpoint,
      indexName,
      new AzureKeyCredential(adminKey),
      { apiVersion: "2023-11-01" }
    );

    for (const queryGroup of data) {
      const queryResultGroup = await searchClient.search(queryGroup.query, searchConfig);

      const obj: AzureCognitiveSearchResponse = {
        query: {
          _id: queryGroup._id,
          input: queryGroup.query,
          results: []
        }
      };

      for await (const result of queryResultGroup.results) {
        if (result.score >= parseFloat(minScore || defaultMinScore)) {
          const resultObj: AzureCognitiveSearchResult = {
            score: result.score,
            document: result.document,
          };

          obj.query.results.push(resultObj);
        }
      }

      searchResults.push(obj);
    }
  } catch (err) {
    console.log(err);
    return NextResponse.json({ message: "从认知搜索API获取数据时发生错误" }, { status: 500 });
  }

  return NextResponse.json({ searchResults }, { status: 200 });
}

关键注意事项

  • 确保Azure认知搜索服务已启用语义搜索(需Standard S3及以上SKU)
  • 搜索索引必须提前配置语义配置(指定语义字段、语言等)
  • 语义检索的得分范围与传统BM25不同(通常0-4),需调整defaultMinScore阈值
  • API版本需在2021-04-30-Preview或更高,你使用的版本满足要求

内容的提问来源于stack exchange,提问作者happycoder2121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:35:30