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

Go语言集成Discovery Engine搜索请求返回空值问题求助

问题分析与修复方案

核心问题点

  • ServingConfig路径格式错误:你在路径末尾加了:search,这是API HTTP方法的后缀,并非资源路径的一部分,必须移除。
  • 未处理Search调用的错误:代码直接接收返回结果,忽略了请求可能失败的情况,这是结果为空的常见原因。
  • Defer Close的位置不当:当前defer discoveryClient.Close()会在函数返回前关闭客户端,而你把客户端赋值给了GCPClient返回给调用方,后续使用会报错。

修正后的代码

package gcp

import (
    "context"
    "fmt"
    "log"
    "virtual-idol-api/config"

    "cloud.google.com/go/storage"
    "google.golang.org/api/option"

    discoveryengine "cloud.google.com/go/discoveryengine/apiv1beta"
    discoveryenginepb "cloud.google.com/go/discoveryengine/apiv1beta/discoveryenginepb"
)

// NewGCPStorageClient creates a new GCPClient and initializes its dependencies based on the environment.
func NewGCPClient(cfg *config.Config) (*GCPClient, error) {
    client := GCPClient{}
    ctx := context.Background()

    discoveryClient, err := discoveryengine.NewSearchClient(ctx)
    if err != nil {
        log.Fatalf("failed to create Discovery client: %s", err)
        return nil, err
    }
    client.DiscoveryClient = discoveryClient

    req := &discoveryenginepb.SearchRequest{
        // 修正ServingConfig路径,移除末尾的:search
        ServingConfig: "projects/12345/locations/global/collections/default_collection/dataStores/test-unstructured_12456/servingConfigs/default_search",
        // 若数据不在默认分支,取消注释并指定正确分支
        // Branch:        "default_branch",

        Query: "who is the president of America",
    }

    // 必须处理Search调用的错误
    res, err := discoveryClient.Search(ctx, req)
    if err != nil {
        log.Printf("search request failed: %s", err)
        discoveryClient.Close()
        return nil, err
    }

    if res == nil || len(res.Results) == 0 {
        log.Println("Search result is empty")
    } else {
        fmt.Printf("%+v\n", res)
    }

    return &client, nil
}

额外检查项

  • 确认你的Data Store已完成数据导入,且索引状态正常。
  • 确认当前客户端使用的服务账号拥有discoveryengine.searcher角色或对应权限。
  • 先通过Gen App Builder控制台测试同一查询,排除数据本身无结果的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:42:47