UnifiedSearch - 通晓统一搜索API

本文介绍UnifiedSearch(通晓统一搜索)的接口参数以及使用方法

接口说明

随着大模型应用的发展,面向Agent的开放域信息查询能力逐渐成为一个基础设施。在此过程中面临一些挑战,包括:

  • 相关性(Relevance):召回结果应避免冲突内容,减少无关信息。进一步,更好地理解复杂查询,以便从召回相关信息进化到召回准确信息。

  • 全面性(Comprehensiveness):能够涵盖各种类型的查询,包括中长尾、多模态、实时信息以及垂类API等。降低客户对多源API的对接成本和路由准确性问题。

  • 成本(Cost):降低每千次调用的费用。

针对上述挑战,UnifiedSearch做了如下调整:

  • 统一多种搜索源:将GenericSearch、GenericAdvancedSearch及未来其他数据源进行统一管理,标准化输入输出,降低使用成本。

  • 动态计量计费:提供灵活计费体系,支持按日保底量的阶梯计费。支持搜索次数和增值包,确保计费按需、透明。

  • 多样化的数据源:在上述基础上,后续会以增值包的形态提供更多的垂类API、高质量数据供给,来优化相关性与全面性。

说明

建议您使用最新的UnifiedSearch接口,后续新的特性将优先在此接口进行迭代;如果您目前使用了GenericSearch、GenericAdvancedSearch、AISearchV2、AiSearchV3等接口,可以无痛的迁移到UnifiedSearch接口。后续所有搜索接口都将统一收敛到UnifiedSearch接口。

接口定义

请求参数

参数

类型

必填

默认值

描述

示例值

query

string

-

搜索问题。取值范围:1~1024个字符。

苹果手机

timeRange

string

NoLimit

查询的时间范围。支持可选值:

  • OneDay:1天内

  • OneWeek:1周内

  • OneMonth:1月内

  • OneYear:1年内

  • NoLimit:无限制(默认值)

NoLimit

category

string

null

查询分类,指定后只返回分类站点的搜索结果,多个行业使用逗号分隔。支持可选值:

  • finance:金融

  • law:法律

  • medical:医疗

  • internet:互联网(精选)

  • tax:税务

  • news_province:新闻省级

  • news_center:新闻中央

engineType

string

Generic

搜索的引擎类型,不同引擎价格与结果会有差异。支持可选值:

  • Generic:标准版搜索,返回10条结果

  • GenericAdvanced:增强版搜索,返回约50条结果,增加权威性站点的召回条数;收费选项

Generic

location

string

null

位置信息,目前支持IP

说明

目前对一些指定的场景效果比较明显,比如天气。会在sceneItems中返回对应地区的天气信息

117.136.110.23

contents

mainText

bool

false

是否返回长正文。

false

markdownText

bool

false

是否返回markdown格式正文。

false

summary

bool

false

是否返回增强摘要。收费选项

false

rerankScore

bool

true

是否进行检索结果的Rerank,并返回rerankScore。

true

返回参数

字段

类型

是否可空

字段说明

样例 (Query: 上海车展最火爆的是哪个品牌

requestId

string

不可空

请求RequestId, 排查问题时可以提供此信息

35E5608A-A737-2038-****-D9D34C6BFD9E

pageItems[]

title

string

不可空

网站标题

上海车展大佬齐聚 问界成为话题中心

link

string

不可空

网站地址

https://hea.china.com/articles/20250427/202504271666343.html

snippet

string

不可空

网页动态摘要,匹配到关键字的部分内容,平均长度150字符

2025上海车展期间,最火爆的无疑是问界品牌,成为众多大佬的话题中心。赛力斯集团董事长(创始人)张兴海、华为常务董事、终端BG董事长余承东、著名演员陈道明、宁德时代董事长曾毓群都分享了对问界的使用体验。 ...

publishedTime

string

可空

网页发布时间,ISO时间格式。

2025-04-27T20:36:04+08:00

mainText

string

可空

解析得到的网页全正文,长度最大3000字符,召回比例超过98%;

说明

开启contents.mainText时返回

2025上海车展期间,最火爆的无疑是问界品牌,成为众多大佬的话题中心。赛力斯集团董事长(创始人)张兴海、华为常务董事、终端BG董事长余承东、著名演员陈道明、宁德时代董事长曾毓群都分享了对问界的使用体验。\n“问界M9、M8正重构 中国 豪华汽车市场格局。”张兴海说, (此处省略....)。\n责任编辑:kj005\n 文章投诉热线:157 3889 8464 投诉邮箱:7983347 1*@qq.com\n关键词:

markdownText

string

可空

解析得到的网页全文markdown格式,对表格等结构化信息有更好的支持,目前召回比例约50%,待持续提高。

说明

开启contents.markdownText时返回

# 上海车展大佬齐聚 问界成为话题中心**来源**:财讯网 **时间**:2025-04-27 20:36:04 2025上海车展期间,最火爆的无疑是问界品牌,成为众多大佬的话题中心。赛力斯集团董事长(创始人)张兴海、华为常务董事、终端BG董事长余承东、著名演员陈道明、宁德时代董事长曾毓群都分享了对问界的使用体验。 ![图片](http://objectnsg.oss-cn-beijing.aliyuncs.com/yhdoc/202504/27/202504272025531927023138.png)余承东表示,问界M9、M8、M7M5,都深受消费者喜爱!问界M9连续3个月中国纯电车型保值率第一!纯电、增程车型包揽新能源大型SUV保值率前两名! ![图片](http://objectnsg.oss-cn-beijing.aliyuncs.com/yhdoc/202504/27/202504272025531312025791.jpeg)“自己是问界M9的用户

*责任编辑:kj005*文章投诉热线: 157 3889 8464 投诉邮箱: 798334***@qq.com

images

string[]

可空

网页中的图片地址,最多三张。

["http://objectnsg.oss-cn-beijing.aliyuncs.com/yhdoc/202504/27/202504272025531927023138.png"]

hostname

string

可空

网页的站点名称

中华网

hostLogo

string

可空

网页的站点Logo

https://www.china.com/zh_cn/img1905/2023/logo.png

summary

string

可空

从网页全正文中提取出与查询(Query)最相关的信息,用于提供增强摘要,默认长度约500

说明

开启contents.summary时返回

2025上海车展期间,最火爆的无疑是问界品牌,成为众多大佬的话题中心。赛力斯集团董事长(创始人)张兴海、华为常务董事、终端BG董事长余承东、著名演员陈道明、宁德时代董事长曾毓群都分享了对问界的使用体验。“自己是问界M9的用户,用车感受非常好。”陈道明表示,体验后才敢现场给大家推荐。未来,希望能实现问界M9的特别定制,让外观、内饰、座椅布局等,更符合自己的使用需求。据悉,2025款问界M9上市25天就交付超1万,已连续11个月蝉联50万元级豪车车销冠;问界M8上市4天,大定就突破了五万 台 ,深受市场任何和用户喜爱...“问界M9、M8正重构 中国 豪华汽车市场格局。”张兴海说, 近 期曾极限试驾问界M8,从重庆出发,历时55小时、行驶超3500公里抵达冈仁波齐。整个行程中,车辆的安全 性 和体验感都表现出色。

rerankScore

double

可空

使用rerank模型对引擎召回结果进行重排序,相关性会有提升。

说明

开启contents.rerankScore时返回,并影响排序

0.7786493301391602

hostAuthorityScore

double

可空

权威性评分,在02之间

说明

只有在请求参数engineType的值为 GenericGenericAdvanced时生效

1.923339

sceneItems[]

type

string

可空

垂类场景结果类型(如天气、时间、日历等),后续会扩展更多类型,参考场景化调用SceneItem概览

重要

垂类场景结果有召回时,可以优先使用此结果,一般都会比网页召回更准确

time

detail

string

可空

垂类场景结果的详情,每种类型结构不同,故此结果是一个JSON结构的字符串。

{\"title\": \"伦敦时间\", \"targetTimeZone\": \"Europe/London\", \"targetTimeMillisecond\": \"1745820817178\", \"targetTime\": \"2025-04-28 14:13:37\", \"beijingTimeZone\": \"PRC\", \"beijingTimeMillisecond\": \"1745846017178\"}

searchInformation

searchTime

int64

不可空

搜索耗时

1048

queryContext

engineType

string

不可空

搜索的引擎类型

Generic

originalQuery

query

string

不可空

原始请求:query

现在伦敦时间

timeRange

string

不可空

原始请求:timeRange

NoLimit

rewrite

enabled

bool

不可空

本次请求是否开启改写

false

timeRange

string

可空

改写后的timeRange,只有改写后的值与原始timeRange不一致时,才会返回。

costCredits

search

genericTextSearch

int32

不可空

基础文本搜索次数;计量计费信息请参考:产品计费

1

valueAdded

summary

int32

不可空

增值包-增强摘要次数

1

advanced

int32

不可空

增值包-增强版搜索次数

0

示例

  • 请求参数(RequestBody)

{
  "query": "上海车展最火爆的是哪个品牌",
  "engineType": "Generic",
  "contents": {
    "mainText": true,
    "markdownText":false,
    "summary": true,
    "rerankScore": true
  }
}
  • 返回参数

{
  "requestId": "5BF6A5A4-CD36-5929-BE81-7E1814D1FBCA",
  "pageItems": [
    {
      "title": "101万人参观上海车展,这50款新车必“火”丨申呼吸",
      "link": "https://auto.ifeng.com/c/8j9ZDODU3Fl",
      "snippet": "今天就来盘点一下,上海车展那些刚亮相或者刚上市就已经爆火的重磅新车。01、梅赛德斯-奔驰CLA长轴版。本届上海车展上,奔驰品牌一举带来了28款车型,其中来自MMA平台的首款车型——全新纯电长轴距CLA首次亮相就赚足了眼球。新车红色的车衣非常惹眼,而且前格栅采用点阵式发光“logo”装饰,代表了这款车的与众不同。02、奥迪E5 Sportback。作为全新AUDI品牌的首款量产车型,奥迪E5 Sportback由奥迪和上汽集团联合研发。这款中型纯电动轿跑既传承了奥迪的品牌基因、设计美学与驾乘体验,又融合了中国市场的数字生态系统与研发速度优势。奥迪E5 Sportback提供后驱及quattro四驱版本,最高功率达579千瓦,零百加速仅需3.4秒,续航里程最高可达770公里。03、一汽丰田bZ5。丰田全新纯电动中型SUV车型bZ5的亮相,标志着丰田在全面电动化、智能化等领域的重要布局。04、广汽丰田铂智7。广汽丰田铂智7是一款非常中国化的新能源车型,在设计和功能方面,广汽丰田铂智7照顾到了了中国市场消费者的审美格调以及日常用车的习惯,新车最大卖点是其搭载了鸿蒙智能座舱,高配车型还搭载了激光雷达,看来智驾能力会是车型的卖点之一。05、东风日产N7。本届上海车展上,东风日产纯电轿车N7主打中国设计研发,智能化方面支持连续语音对话,8295P芯片,Momenta智驾,甚至800V平台,这些新势力有的它都有,而且11.99万元的起售价格,为消费者带来了足够的诚意。",
      "publishedTime": null,
      "mainText": null,
      "markdownText": null,
      "images": [],
      "hostname": null,
      "hostLogo": null,
      "summary": null,
      "rerankScore": 0.7411223012005077,
      "hostAuthorityScore": null
    },
    {
      "title": "千家企业参加上海车展,宝马的展台竟成了“人气王”?",
      "link": "https://news.m.yiche.com/hao/wenzhang/99995741/",
      "snippet": "如果要问上海车展哪个展台最火爆?宝马无疑是其中之一! 本届车展,宝马集团携带旗下三大品牌BMW、 MINI 与BMW Motorrad超30款新车型与多项独创新技术亮相。但宝马展台之所以引来众多参展人员的围观,不是因为它的产品阵容有多强大,而是它的创新成果,点燃了大家的好奇心,带来前所未有的惊喜。",
      "publishedTime": "2025-04-23T20:31:00+08:00",
      "mainText": null,
      "markdownText": null,
      "images": [
        "https://img8.bitautoimg.com/usercenter/mapi/news/2025/04/23/w800_m1_yichecar_0c34b3114f4a49579edf064d066527d6.jpeg.webp"
      ],
      "hostname": "易车网",
      "hostLogo": null,
      "summary": null,
      "rerankScore": 0.7183914914433365,
      "hostAuthorityScore": 1.987037
    },
    {
      "title": "101万人参观上海车展,这50款新车必“火”丨申呼吸",
      "link": "https://m.163.com/dy/article/JUTF5R1T0527W3NV.html",
      "snippet": "今天就来盘点一下,上海车展那些刚亮相或者刚上市就已经爆火的重磅新车。01、梅赛德斯-奔驰CLA长轴版 本届上海车展上,奔驰品牌一举带来了28款车型,其中来自MMA平台的首款车型—全新纯电...",
      "publishedTime": "2025-05-07T05:55:32+08:00",
      "mainText": null,
      "markdownText": null,
      "images": [
        "https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2025%2F0507%2F5b7ed28aj00svuzoe002hd000ic013om.jpg&thumbnail=660x2147483647&quality=80&type=jpg"
      ],
      "hostname": "网易",
      "hostLogo": "https://s2.zimgs.cn/ims?kt=url&at=smstruct&key=aHR0cDovL20uMTYzLmNvbS9mYXZpY29uLmljbw==&sign=yx:oT1erCQejExBeYcppA0kvJkAl_Y=&tv=400_400",
      "summary": null,
      "rerankScore": 0.689543213123283,
      "hostAuthorityScore": 1.006774
    },
    {
      "title": "上海车展新势力品牌最热门新车TOP10:问界M8第一",
      "link": "https://m.sohu.com/a/890926551_115831/?pvid=000115_3w_a",
      "snippet": "CNMO注意到,据相关机构统计,上海车展中国新势力品牌最热门新车TOP10榜单中,问界M8的关注人数遥遥领先,位居第一。而就在4月29日,鸿蒙智行官方宣布,旗下家庭旗舰SUV问界M8的累计大定订单已经突破6万份。",
      "publishedTime": "2025-04-30T16:57:00+08:00",
      "mainText": null,
      "markdownText": null,
      "images": [
        "https://q4.itc.cn/q_70/images03/20250430/02f2016873d8414ba32319b33cd1e186.png",
        "https://q0.itc.cn/q_70/images03/20250430/704b5fee93e44f7c97ce1ce69dfbbdd4.png"
      ],
      "hostname": "搜狐网",
      "hostLogo": "https://s2.zimgs.cn/ims?kt=url&at=smstruct&key=aHR0cHM6Ly9ndy5hbGljZG4uY29tL0wxLzcyMy8xNTg0MzI5MTIyL2ZhLzdiL2QwL2ZhN2JkMGM2MTlhODM2NmIwNzNkNWM3ZWQ0ZWFhNWUwLmljbw==&sign=yx:C1HunXUgWw_Hnydsxo7hNSZ08AU=&tv=400_400",
      "summary": null,
      "rerankScore": 0.6704316013572356,
      "hostAuthorityScore": 1.034545
    },
    {
      "title": "关注 | 上海车展最火、抗寒能力最强,为什么是吉利?",
      "link": "https://hj.pcauto.com.cn/wap/article/222387.html",
      "snippet": "2019年可以说是吉利汽车的市场大年。过完年后,吉利基本上保持月月都有至少一款新车上市。而在上海车展上,吉利展台无疑是最火爆的展台之一。那么,吉利汽车究竟凭借什么吸引火爆人气?又是凭借什么稳居自主一哥地位? 0  1  拥有...",
      "publishedTime": "2024-07-28T00:00:00+08:00",
      "mainText": null,
      "markdownText": null,
      "images": [
        "https://img.pcauto.com.cn/images/wxauto/3FE728E89D225468C7CA10E2E8F372FC/mmbiz_jpg/1F9RP41zbE4iaSJcpu8lrj0iazsm1UadXa9VS52VnXPoNmlLEvSgtZbhuzPR9H4ftS4yJicV7tpe5WGOkpDFbzheQ_640x480.jpg",
        "https://img.pcauto.com.cn/images/wxauto/3FE728E89D225468C7CA10E2E8F372FC/mmbiz_jpg/1F9RP41zbE4iaSJcpu8lrj0iazsm1UadXa9SeDlSjlpJiaC0aIxNEQ9jTGDsvVUwB0jrBIzfx7yqrNBsVPuiaJNyLw_640x480.jpg",
        "https://img.pcauto.com.cn/images/wxauto/3FE728E89D225468C7CA10E2E8F372FC/mmbiz_jpg/1F9RP41zbE4iaSJcpu8lrj0iazsm1UadXa9OHlGTuKYC4zrRBO5NOsgvCK1libJKMkjCQwC2q1shqqRaWPgDJVLcw_640x480.jpg"
      ],
      "hostname": "行家号(太平洋汽车网)",
      "hostLogo": null,
      "summary": null,
      "rerankScore": 0.6624916631961777,
      "hostAuthorityScore": 1.975463
    },
    {
      "title": "上海车展零跑爆火!70万辆交付量,新势力销量冠军实锤!",
      "link": "https://baijiahao.baidu.com/s?id=1830888039972556213",
      "snippet": "零跑汽车以一季度70万辆交付量、3月37095辆的销量冠军成绩,成为上海车展焦点。C01车型凭借流畅设计、澎湃动力和精准操控,展现强劲实力。品牌以亲民价格和精准市场洞察,稳居新势力前三,未来可期。有用 上海车展,人声鼎沸,宛如一场盛大的汽车嘉年华。各大厂商纷纷亮出看家本领,争夺人们的视线。然而,真正引人注目的,却是零跑汽车异军突起,成为展会当之无愧的焦点。这并非偶然,而是实力的集中爆发。今年一季度,零跑累计交付量突破70万辆,3月份更是一举夺得新势力",
      "publishedTime": "2025-05-01T11:41:00+08:00",
      "mainText": null,
      "markdownText": null,
      "images": [
        "https://pics3.baidu.com/feed/b21bb051f8198618528834ceb98ee97c8ad4e625.jpeg@f_auto?token=3e10155ac757d7fae5cb0d39e0a5acef"
      ],
      "hostname": "百家号",
      "hostLogo": "https://s2.zimgs.cn/ims?kt=url&at=smstruct&key=aHR0cHM6Ly9ndy5hbGljZG4uY29tL0wxLzcyMy8xNTY4MDg2OTQ1L2ZmLzI4L2QyL2ZmMjhkMmRlMjcxODIxOGNjZDE0YTI4ZDVkN2ZkZmE3LnBuZw==&sign=yx:1BNGL1hDklXfMpORbNzpnbj36JM=&tv=400_400",
      "summary": null,
      "rerankScore": 0.6513487581674036,
      "hostAuthorityScore": 1.012268
    },
    {
      "title": "本届上海车展最火车型出炉,纯电动SUV成了各大品牌的香饽饽",
      "link": "https://chejiahao.m.autohome.com.cn/info/16685011",
      "snippet": "知名品牌宝马、福特、凯迪拉克等都是如此。宝马 iX 4月18日,宝马在上海举行了“宝马集团之夜”,抢在车展前夕发布了全新纯电动中大型SUV宝马 iX,并在车展再次登场。这款车是 iNext(...",
      "publishedTime": "2025-01-31T15:14:00+08:00",
      "mainText": null,
      "markdownText": null,
      "images": [],
      "hostname": "汽车之家",
      "hostLogo": "https://s2.zimgs.cn/ims?kt=url&at=smstruct&key=aHR0cHM6Ly9jZG4uc20uY24vdGVtcC8yMDI0MTAyMzE2MTQxMy1xYjFoYjdidHMwb2Jvazg4d2k2enpyN3dwaXF5N3dwYS5qcGc=&sign=yx:ZYgShfjBFYPG0BCQpjDUXT7QD90=&tv=400_400",
      "summary": null,
      "rerankScore": 0.6283403741670196,
      "hostAuthorityScore": 1.992469
    },
    {
      "title": "上海车展最火的3款豪华SUV:富哥都馋哭了",
      "link": "https://news.m.yiche.com/hao/wenzhang/100156579/",
      "snippet": "今年的上海车展,又创造了自主品牌车企的“数量之最”,车型数量达到了一个新的巅峰,尤其是在豪华车型方面,很多车企都拿出了最新的款式,更是实现了向上突破!现在,车展已经进入尾声了,我们车314也来给大家整点复盘梳理,这次就来聊...",
      "publishedTime": "2025-04-29T11:07:00+08:00",
      "mainText": null,
      "markdownText": null,
      "images": [],
      "hostname": "易车网",
      "hostLogo": null,
      "summary": null,
      "rerankScore": 0.5695837399009553,
      "hostAuthorityScore": 1.987037
    }
  ],
  "sceneItems": [],
  "searchInformation": {
    "searchTime": 1176
  },
  "queryContext": {
    "engineType": "Generic",
    "originalQuery": {
      "query": "上海车展最火爆的是哪个品牌",
      "timeRange": "NoLimit"
    },
    "rewrite": {
      "enabled": true,
      "timeRange": null
    }
  },
  "costCredits": {
    "search": {
      "genericTextSearch": 1,
      "liteTextSearch": 0,
      "liteAdvancedTextSearch": 0
    },
    "valueAdded": {
      "summary": 0,
      "advanced": 0
    }
  }
}

错误码

Status

错误码

错误信息

处理方案

404

InvalidAccessKeyId.NotFound

Specified access key is not found.

检查并确保AccessKey/Secret正确。

403

Retrieval.NotActivate

Please activate AI search service

请下单或联系您的客户经理进行开通。

403

Retrieval.Arrears

Please recharge first.

账户金额不足,请充值

403

Retrieval.NotAuthorised

Please authorize the AliyunIQSFullAccess privilege to the sub-account.

子账号没有进行授权,参考创建RAM用户并授权

403

Retrieval.TestUserPeriodExpired

The test period has expired.

测试已到期(自下单后15天有效),可以联系阿里云客户经理转正式

429

Retrieval.Throttling.User

Request was denied due to user flow control.

超出限流规格,可联系阿里云客户经理进行升配

429

Retrieval.TestUserQueryPerDayExceeded

The query per day exceed the limit.

测试超出日限额(1000次/天),可以联系阿里云客户经理转正式

接口调用

SDK调用

使用阿里云AK/SK认证方式,并使用阿里云SDK发起接口调用

Python SDK

前提条件

您需要确保已安装Python3.8或以上版本。

安装SDK
pip3 install alibabacloud_iqs20241111==1.4.3
调用代码
  • 同步调用

import os

from Tea.exceptions import TeaException
from alibabacloud_iqs20241111 import models
from alibabacloud_iqs20241111.client import Client
from alibabacloud_tea_openapi import models as open_api_models


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> Client:
        config = open_api_models.Config(
            # TODO: 使用您的AK/SK进行替换(建议通过环境变量加载)
            access_key_id='$YOUR_ACCESS_KEY',
            access_key_secret='$YOUR_ACCESS_SECRET'
        )
        config.endpoint = f'iqs.cn-zhangjiakou.aliyuncs.com'
        return Client(config)

    @staticmethod
    def main() -> None:
        client = Sample.create_client()
        run_instances_request = models.UnifiedSearchRequest(
            body=models.UnifiedSearchInput(
                query='杭州美食',
                time_range='NoLimit',
                contents=models.RequestContents(
                    summary=True,
                    main_text=True,
                )
            )
        )
        try:
            response = client.unified_search(run_instances_request)
            print(
                f"api success, request_id:{response.body.request_id}, size :{len(response.body.page_items)}, server_cost:{response.body.search_information.search_time}")
            if len(response.body.scene_items) > 0:
                print(f"scene_items:{response.body.scene_items[0]}")
            for index, item in enumerate(response.body.page_items):
                print(f"{index}. {'-' * 20}")
                print(f"title:{item.title}")
                print(f"snippet:{item.snippet}")
                print(f"summary:{item.summary}")
                print(f"published_time:{item.published_time}")
                print(f"link:{item.link}")
                print(f"rerank_score:{item.rerank_score}")

        except TeaException as e:
            code = e.code
            request_id = e.data.get("requestId")
            message = e.data.get("message")
            print(f"api exception, requestId:{request_id}, code:{code}, message:{message}")


if __name__ == '__main__':
    Sample.main()
  • 异步调用

import asyncio
import os
import time

from Tea.exceptions import TeaException
from alibabacloud_iqs20241111 import models
from alibabacloud_iqs20241111.client import Client
from alibabacloud_tea_openapi import models as open_api_models


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client() -> Client:
        config = open_api_models.Config(
            # TODO: 使用您的AK/SK进行替换(建议通过环境变量加载)
            access_key_id=os.environ.get('ACCESS_KEY'),
            access_key_secret=os.environ.get('ACCESS_SECRET')

        )
        config.endpoint = f'iqs.cn-zhangjiakou.aliyuncs.com'
        return Client(config)

    @staticmethod
    async def main_async() -> None:
        start = time.time()
        client = Sample.create_client()
        run_instances_request = models.UnifiedSearchRequest(
            body=models.UnifiedSearchInput(
                query='杭州美食',
                time_range='NoLimit',
                contents=models.RequestContents(
                    summary=True,
                    main_text=True,
                )
            )
        )
        try:
            # 使用异步方法
            response = await client.unified_search_async(run_instances_request)
            print(
                f"api success, request_id:{response.body.request_id}, size :{len(response.body.page_items)}, server_cost:{response.body.search_information.search_time}")
            if len(response.body.scene_items) > 0:
                print(f"scene_items:{response.body.scene_items[0]}")
            for index, item in enumerate(response.body.page_items):
                print(f"{index}. {'-' * 20}")
                print(f"title:{item.title}")
                print(f"snippet:{item.snippet}")
                print(f"summary:{item.summary}")
                print(f"published_time:{item.published_time}")
                print(f"link:{item.link}")
                print(f"rerank_score:{item.rerank_score}")
        except TeaException as e:
            code = e.code
            request_id = e.data.get("requestId")
            message = e.data.get("message")
            print(f"api exception, requestId:{request_id}, code:{code}, message:{message}")

if __name__ == '__main__':
    asyncio.run(Sample.main_async())

Java SDK

前提条件

已安装Java8或以上版本。

Maven依赖
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>iqs20241111</artifactId>
    <version>1.4.3</version>
</dependency>
调用代码
package com.aliyun.iqs.example;

import com.aliyun.iqs20241111.Client;
import com.aliyun.iqs20241111.models.*;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class UnifiedSearchExample {
    public static void main(String[] args) throws Exception {
        Client client = initClient();
        invoke(client, "杭州美食", "NoLimit");
    }

    private static Client initClient() throws Exception {
        // TODO: 使用您的AK/SK进行替换(建议通过环境变量加载)
        String accessKeyId = "$YOUR_ACCESS_KEY";
        String accessKeySecret = "$YOUR_ACCESS_SECRET";
        
        Config config = new Config()
            .setAccessKeyId(accessKeyId)
            .setAccessKeySecret(accessKeySecret);

        config.setEndpoint("iqs.cn-zhangjiakou.aliyuncs.com");
        return new Client(config);
    }

    private static void invoke(Client client, String query, String timeRange) {
        UnifiedSearchInput input = new UnifiedSearchInput();
        input.setQuery(query);
        input.setTimeRange(timeRange);

        RequestContents requestContents = new RequestContents().setSummary(true).setMainText(true);
        input.setContents(requestContents);
        UnifiedSearchRequest request = new UnifiedSearchRequest().setBody(input);

        try {
            UnifiedSearchResponse response = client.unifiedSearch(request);
            UnifiedSearchOutput result = response.getBody();

            printOutput(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void printOutput(UnifiedSearchOutput output) {
        // 使用 GsonBuilder 创建带格式化的 Gson 实例
        Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .disableHtmlEscaping()
            .create();

        // 输出格式化的 JSON
        String prettyJson = gson.toJson(output);
        System.out.println(prettyJson);
    }
}

Go SDK

前提条件

Go 环境版本必须不低于 1.10.x

安装SDK
require (
  github.com/alibabacloud-go/iqs-20241111 v1.4.3
  github.com/alibabacloud-go/darabonba-openapi/v2 v2.0.10
)
调用代码
package main

import (
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	iqs20241111 "github.com/alibabacloud-go/iqs-20241111/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"log"
)

const endpointURL = "iqs.cn-zhangjiakou.aliyuncs.com"

func createClient() (*iqs20241111.Client, error) {
	// TODO: 使用您的AK/SK进行替换
	accessKeyID := "YOUR_ACCESS_KEY"
	accessKeySecret := "YOUR_ACCESS_SECRET"

	if accessKeyID == "" || accessKeySecret == "" {
		return nil, fmt.Errorf("ACCESS_KEY or ACCESS_SECRET environment variable is not set")
	}

	config := &openapi.Config{
		AccessKeyId:     tea.String(accessKeyID),
		AccessKeySecret: tea.String(accessKeySecret),
		Endpoint:        tea.String(endpointURL),
	}

	return iqs20241111.NewClient(config)
}

func runGenericSearch(client *iqs20241111.Client) error {
	body := &iqs20241111.UnifiedSearchInput{
		Query:     tea.String("杭州美食"),
		TimeRange: tea.String("NoLimit"),
		Contents: &iqs20241111.RequestContents{
			Summary:  tea.Bool(true),
			MainText: tea.Bool(true),
		},
	}
	request := &iqs20241111.UnifiedSearchRequest{
		body,
	}
	runtime := &util.RuntimeOptions{}

	resp, err := client.UnifiedSearchWithOptions(request, nil, runtime)
	if err != nil {
		return fmt.Errorf("generic search failed: %w", err)
	}

	fmt.Printf("[%s] response: %s\n", *resp.Body.RequestId, resp.Body)
	return nil
}

func main() {
	client, err := createClient()
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	if err := runGenericSearch(client); err != nil {
		log.Fatalf("Error running generic search: %v", err)
	}
}

HTTP调用

使用信息查询服务(IQS)产品的凭证(API-KEY)进行认证,并使用HTTP发起接口调用。创建并查看凭证,获取API-KEY。

curl  -X POST https://cloud-iqs.aliyuncs.com/search/unified \
--header "Authorization: Bearer $API_KEY" \
--header "Content-Type: application/json" \
--data '{
  "query": "杭州美食",
  "engineType": "Generic",
  "contents": {
    "mainText": true,
    "markdownText":false,
    "summary": true,
    "rerankScore": true
  }
}'
重要

$API_KEY 替换为信息查询服务控制台中创建的API-KEY,创建并查看凭证创建API-KEY需要等待5min生效。