OpenSearchService.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. <?php
  2. // api-v8/app/Services/OpenSearchService.php
  3. namespace App\Services;
  4. use App\Facades\RedisCache;
  5. use Exception;
  6. use GuzzleHttp\Client;
  7. use Illuminate\Support\Facades\Log;
  8. use Illuminate\Support\Str;
  9. use OpenSearch\GuzzleClientFactory;
  10. class OpenSearchService
  11. {
  12. private const EMBEDDING_CACHE_VERSION_KEY = 'embedding/version';
  13. protected $client;
  14. protected $http;
  15. protected $openaiApiKey;
  16. /**
  17. * 默认查询排除字段
  18. *
  19. * @var array
  20. */
  21. private $sourceExcludes = [
  22. 'title.suggest.pali',
  23. 'title.suggest.zh',
  24. 'content.suggest.pali',
  25. 'content.suggest.zh',
  26. 'content.display', // 新增,列表页不返回 HTML
  27. ];
  28. /**
  29. * 默认权重配置
  30. *
  31. * fuzzy / hybrid 两种模式各自的字段权重。
  32. * hybrid 额外包含 fuzzy_ratio / semantic_ratio 用于控制两路得分的混合比例。
  33. *
  34. * 字段名已按新映射结构调整:
  35. * title.text.pali → 原 title.pali.text
  36. * title.text.zh → 原 title.zh
  37. * content.text.pali → 原 content.pali.text
  38. * content.text.zh → 原 content.zh
  39. *
  40. * @var array
  41. */
  42. private $weights = [
  43. 'fuzzy' => [
  44. 'bold_single' => 50,
  45. 'bold_multi' => 10,
  46. 'title.text.pali' => 3,
  47. 'title.text.zh' => 3,
  48. 'summary.text' => 2,
  49. 'content.text.pali' => 1,
  50. 'content.text.zh' => 1,
  51. ],
  52. 'hybrid' => [
  53. 'fuzzy_ratio' => 0.7,
  54. 'semantic_ratio' => 0.3,
  55. 'bold_single' => 50,
  56. 'bold_multi' => 10,
  57. 'title.text.pali' => 3,
  58. 'title.text.zh' => 3,
  59. 'summary.text' => 2,
  60. 'content.text.pali' => 1,
  61. 'content.text.zh' => 1,
  62. ],
  63. ];
  64. /**
  65. * OpenSearch 索引定义(settings + mappings)
  66. *
  67. * 字段结构说明:
  68. *
  69. * title
  70. * ├── text
  71. * │ ├── pali (text) 模糊查询 + exact subfield 精确查询
  72. * │ └── zh (text) 中文分词查询
  73. * ├── vector (knn_vector, dim=1536)
  74. * └── suggest
  75. * ├── pali (completion)
  76. * └── zh (completion)
  77. *
  78. * content(结构与 title 一致,额外包含 tokens nested 字段)
  79. * ├── text
  80. * │ ├── pali (text)
  81. * │ └── zh (text)
  82. * ├── tokens (nested)
  83. * ├── vector (knn_vector, dim=1536)
  84. * └── suggest
  85. * ├── pali (completion)
  86. * └── zh (completion)
  87. *
  88. * summary(中文摘要,结构保持不变)
  89. * ├── text (text)
  90. * └── vector (knn_vector, dim=1536)
  91. *
  92. * 分类维度(resource_id、resource_type、language 等)一律 keyword:它们是枚举值,
  93. * 不该被分词。若声明成 text,'zh-Hans' 会被切成 zh + hans,查 language=zh
  94. * 就会把 zh-Hans 的文档一并捞进来(实测 401 vs 410),而且不报错。
  95. *
  96. * 定义本身在 opensearch/indices/{index}.json,见 indexDefinition()。
  97. */
  98. private ?array $indexDefinition = null;
  99. /**
  100. * 读取索引定义(settings + mappings)
  101. *
  102. * 文件名与索引名一致:{index_definition_path}/{index}.json,
  103. * 默认目录为仓库根目录的 opensearch/indices/。换索引版本时新增一个同名 JSON。
  104. *
  105. * @return array{settings: array, mappings: array}
  106. *
  107. * @throws Exception 文件不存在或不是合法 JSON 时抛出
  108. */
  109. protected function indexDefinition(): array
  110. {
  111. if ($this->indexDefinition !== null) {
  112. return $this->indexDefinition;
  113. }
  114. $path = Str::finish(config('mint.opensearch.index_definition_path'), '/')
  115. .config('mint.opensearch.index').'.json';
  116. if (! is_file($path)) {
  117. throw new Exception("OpenSearch index definition [$path] not found.");
  118. }
  119. return $this->indexDefinition = json_decode(file_get_contents($path), true, flags: JSON_THROW_ON_ERROR);
  120. }
  121. /**
  122. * 创建 OpenSearchService 实例
  123. *
  124. * 从 config('mint.opensearch.config') 读取连接配置,
  125. * 同时初始化 OpenAI HTTP 客户端用于 embedding 调用。
  126. */
  127. public function __construct()
  128. {
  129. $config = config('mint.opensearch.config');
  130. $hostUrl = "{$config['scheme']}://{$config['host']}:{$config['port']}";
  131. $this->client = (new GuzzleClientFactory)->create([
  132. 'base_uri' => $hostUrl,
  133. 'auth' => [$config['username'], $config['password']],
  134. 'verify' => $config['ssl_verification'],
  135. ]);
  136. $this->openaiApiKey = env('OPENAI_API_KEY');
  137. $this->http = new Client([
  138. 'base_uri' => 'https://api.openai.com/v1/',
  139. 'timeout' => 15,
  140. ]);
  141. }
  142. /**
  143. * 动态覆盖指定搜索模式的字段权重
  144. *
  145. * @param string $mode 搜索模式,支持 'fuzzy' | 'hybrid'
  146. * @param array $weights 需要覆盖的权重键值对,例如:['title.text.pali' => 5]
  147. */
  148. public function setWeights(string $mode, array $weights): void
  149. {
  150. if (isset($this->weights[$mode])) {
  151. $this->weights[$mode] = array_merge($this->weights[$mode], $weights);
  152. }
  153. }
  154. /**
  155. * 测试与 OpenSearch 集群的连接状态
  156. *
  157. * @return array{0: bool, 1: string} [连接是否成功, 描述信息]
  158. */
  159. public function testConnection(): array
  160. {
  161. try {
  162. $info = $this->client->info();
  163. $message = 'OpenSearch 连接成功: '.json_encode($info['version']['number']);
  164. Log::info($message);
  165. return [true, $message];
  166. } catch (Exception $e) {
  167. $message = 'OpenSearch 连接失败: '.$e->getMessage();
  168. Log::error($message);
  169. return [false, $message];
  170. }
  171. }
  172. /**
  173. * 检查当前索引是否已存在
  174. */
  175. public function indexExists(): bool
  176. {
  177. $index = config('mint.opensearch.index');
  178. return $this->client->indices()->exists(['index' => $index]);
  179. }
  180. /**
  181. * 创建 OpenSearch 索引
  182. *
  183. * 使用 indexDefinition() 读到的 settings 和 mappings 创建索引。
  184. * 若索引已存在则抛出异常,避免覆盖生产数据。
  185. *
  186. * @return array OpenSearch 响应
  187. *
  188. * @throws Exception 索引已存在时抛出
  189. */
  190. public function createIndex(): array
  191. {
  192. $index = config('mint.opensearch.index');
  193. $exists = $this->client->indices()->exists(['index' => $index]);
  194. if ($exists) {
  195. throw new Exception("Index [$index] already exists.");
  196. }
  197. return $this->client->indices()->create([
  198. 'index' => $index,
  199. 'body' => $this->indexDefinition(),
  200. ]);
  201. }
  202. /**
  203. * 更新已有索引的 settings 和 mappings
  204. *
  205. * 更新 settings 时会临时关闭索引(close → putSettings → open),
  206. * 更新 mappings 支持热更新(新增字段),不可修改已有字段类型。
  207. *
  208. * @return array 包含 'settings' 和/或 'mappings' 的响应数组
  209. */
  210. public function updateIndex(): array
  211. {
  212. $index = config('mint.opensearch.index');
  213. $settings = $this->indexDefinition()['settings'] ?? [];
  214. $mappings = $this->indexDefinition()['mappings'] ?? [];
  215. $response = [];
  216. if (! empty($settings)) {
  217. $this->client->indices()->close(['index' => $index]);
  218. $response['settings'] = $this->client->indices()->putSettings([
  219. 'index' => $index,
  220. 'body' => ['settings' => $settings],
  221. ]);
  222. $this->client->indices()->open(['index' => $index]);
  223. }
  224. if (! empty($mappings)) {
  225. $response['mappings'] = $this->client->indices()->putMapping([
  226. 'index' => $index,
  227. 'body' => $mappings,
  228. ]);
  229. }
  230. return $response;
  231. }
  232. /**
  233. * 切换 pali 同义词文件版本
  234. *
  235. * 把 pali_synonyms filter 的 synonyms_path 指向
  236. * analysis/pali-synonyms-{$version}.txt(文件须已存在于 OpenSearch
  237. * 各节点的 config 目录中,否则索引无法重新打开)。
  238. *
  239. * synonyms_path 属于静态 settings,必须 close → putSettings → open。
  240. * 无论 putSettings 成功与否都会尝试重新打开索引,避免索引停留在 close 状态。
  241. *
  242. * @param string $version 版本号,仅允许 [A-Za-z0-9._-]
  243. * @return array{path: string, settings: array} 新路径与 OpenSearch 响应
  244. *
  245. * @throws Exception 版本号非法、索引不存在或 OpenSearch 拒绝时抛出
  246. *
  247. * @example
  248. * $service->updatePaliSynonymsPath('20260731');
  249. */
  250. public function updatePaliSynonymsPath(string $filename): array
  251. {
  252. $index = config('mint.opensearch.index');
  253. if (! $this->client->indices()->exists(['index' => $index])) {
  254. throw new Exception("Index [$index] does not exist.");
  255. }
  256. $path = Str::finish(config('mint.opensearch.config.synonyms_path'), '/').$filename;
  257. Log::debug('OpenSearchService::updatePaliSynonymsPath', [
  258. 'index' => $index,
  259. 'synonyms_path' => $path,
  260. ]);
  261. // 以代码中的 analysis 定义为准,只替换同义词文件路径
  262. $analysis = $this->indexDefinition()['settings']['analysis'];
  263. $analysis['filter']['pali_synonyms']['synonyms_path'] = $path;
  264. $this->client->indices()->close(['index' => $index]);
  265. try {
  266. $response = $this->client->indices()->putSettings([
  267. 'index' => $index,
  268. 'body' => ['settings' => ['analysis' => $analysis]],
  269. ]);
  270. } finally {
  271. $this->client->indices()->open(['index' => $index]);
  272. }
  273. return ['path' => $path, 'settings' => $response];
  274. }
  275. /**
  276. * 读取当前索引使用的 pali 同义词文件路径
  277. *
  278. * @return string|null 形如 "analysis/pali-synonyms-20260731.txt",未设置时返回 null
  279. */
  280. public function getPaliSynonymsPath(): ?string
  281. {
  282. return $this->getPaliSynonymsSetting()['synonyms_path'] ?? null;
  283. }
  284. /**
  285. * 读取当前索引 pali_synonyms filter 的完整设置
  286. *
  287. * @return array{type?: string, synonyms_path?: string, updateable?: string}|null 未设置时返回 null
  288. */
  289. public function getPaliSynonymsSetting(): ?array
  290. {
  291. $index = config('mint.opensearch.index');
  292. $settings = $this->client->indices()->getSettings(['index' => $index]);
  293. return $settings[$index]['settings']['index']['analysis']['filter']['pali_synonyms'] ?? null;
  294. }
  295. /**
  296. * 删除当前索引
  297. *
  298. * @return array OpenSearch 响应
  299. */
  300. public function deleteIndex(): array
  301. {
  302. $index = config('mint.opensearch.index');
  303. return $this->client->indices()->delete(['index' => $index]);
  304. }
  305. /**
  306. * 统计索引文档数量(支持可选条件过滤)
  307. *
  308. * @param array|null $query OpenSearch DSL query 子句,为 null 时统计全部文档。
  309. * 示例:['term' => ['language' => 'zh']]
  310. * ['exists' => ['field' => 'content.vector']]
  311. * @return int 文档总数
  312. *
  313. * @throws Exception
  314. *
  315. * @example
  316. * $service->count();
  317. * $service->count(['exists' => ['field' => 'content.vector']]);
  318. */
  319. public function count(?array $query = null): int
  320. {
  321. $index = config('mint.opensearch.index');
  322. $params = ['index' => $index];
  323. if (! empty($query)) {
  324. $params['body'] = ['query' => $query];
  325. }
  326. $response = $this->client->count($params);
  327. return (int) ($response['count'] ?? 0);
  328. }
  329. /**
  330. * 写入或覆盖单条文档
  331. *
  332. * @param string $id 文档 ID
  333. * @param array $body 文档内容,字段结构须与 mappings 一致
  334. * @return array OpenSearch 响应
  335. */
  336. public function create(string $id, array $body): array
  337. {
  338. return $this->client->index([
  339. 'index' => config('mint.opensearch.index'),
  340. 'id' => $id,
  341. 'body' => $body,
  342. ]);
  343. }
  344. /**
  345. * 删除单条文档
  346. *
  347. * @param string $id 文档 ID
  348. * @return array OpenSearch 响应
  349. */
  350. public function delete(string $id): array
  351. {
  352. return $this->client->delete([
  353. 'index' => config('mint.opensearch.index'),
  354. 'id' => $id,
  355. ]);
  356. }
  357. /**
  358. * 执行高级搜索
  359. *
  360. * 支持五种搜索模式:
  361. * - fuzzy 多字段模糊查询(默认),巴利文走三层排序
  362. * - exact 精确匹配,使用 markdown_clean analyzer
  363. * - semantic 纯语义向量搜索,需要 OpenAI embedding
  364. * - hybrid fuzzy + semantic 混合,权重由 fuzzy_ratio / semantic_ratio 控制
  365. * - definition 定义查询,黑体字(bold_single/bold_multi)高权重,术语定义排前
  366. *
  367. * 支持的过滤参数:
  368. * resourceType, resourceId, granularity, language, category,
  369. * tags, pageRefs, relatedId, author, channel
  370. *
  371. * @param array $params {
  372. *
  373. * @type string $query 搜索关键词(必填)
  374. * @type string $searchMode 搜索模式,默认 'fuzzy'
  375. * @type int $page 页码,默认 1
  376. * @type int $pageSize 每页条数,默认 20
  377. * @type string $resourceType 按资源类型过滤
  378. * @type string $resourceId 按资源 ID 过滤
  379. * @type string $granularity 按粒度过滤
  380. * @type string $language 按语言过滤
  381. * @type string $category 按分类过滤
  382. * @type array $tags 按标签过滤(terms)
  383. * @type array $pageRefs 按页码引用过滤(terms)
  384. * @type string|array $relatedId 按关联 ID 过滤(数组时命中任一)
  385. * @type string $author 按作者过滤
  386. * @type string $channel 按频道过滤(channel uuid)
  387. * @type bool $aggregations 是否计算分面聚合,默认 true
  388. * @type array $highlight_pre_tags 高亮前置标签,默认 ['<mark>']
  389. * @type array $highlight_post_tags 高亮后置标签,默认 ['</mark>']
  390. * }
  391. *
  392. * @return array OpenSearch 原始响应
  393. *
  394. * @throws Exception semantic / hybrid 模式下 embedding 调用失败时抛出
  395. */
  396. public function search(array $params): array
  397. {
  398. $page = $params['page'] ?? 1;
  399. $pageSize = $params['pageSize'] ?? 20;
  400. $from = ($page - 1) * $pageSize;
  401. $mode = $params['searchMode'] ?? 'fuzzy';
  402. // 排除字段
  403. if (! empty($params['excludes']) && is_array($params['excludes'])) {
  404. $excludes = array_merge($this->sourceExcludes, $params['excludes']);
  405. } else {
  406. $excludes = $this->sourceExcludes;
  407. }
  408. // ---------- 过滤条件 ----------
  409. $filters = [];
  410. if (! empty($params['resourceType'])) {
  411. $filters[] = ['term' => ['resource_type' => $params['resourceType']]];
  412. }
  413. if (! empty($params['resourceId'])) {
  414. $filters[] = ['term' => ['resource_id' => $params['resourceId']]];
  415. }
  416. if (! empty($params['granularity'])) {
  417. $filters[] = ['term' => ['granularity' => $params['granularity']]];
  418. }
  419. if (! empty($params['language'])) {
  420. $filters[] = ['term' => ['language' => $params['language']]];
  421. }
  422. if (! empty($params['category'])) {
  423. if (is_array($params['category'])) {
  424. $categories = $params['category'];
  425. } else {
  426. $categories = [$params['category']];
  427. }
  428. // 必须匹配全部:为每个 category 创建一个 term 条件
  429. foreach ($categories as $category) {
  430. $filters[] = ['term' => ['category' => $category]];
  431. }
  432. }
  433. if (! empty($params['tags'])) {
  434. $filters[] = ['terms' => ['tags' => $params['tags']]];
  435. }
  436. if (! empty($params['pageRefs'])) {
  437. $filters[] = ['terms' => ['page_refs' => $params['pageRefs']]];
  438. }
  439. if (! empty($params['relatedId'])) {
  440. $filters[] = is_array($params['relatedId'])
  441. ? ['terms' => ['related_id' => array_values($params['relatedId'])]]
  442. : ['term' => ['related_id' => $params['relatedId']]];
  443. }
  444. if (! empty($params['author'])) {
  445. $filters[] = ['match' => ['metadata.author' => $params['author']]];
  446. }
  447. // metadata.channel 在映射里是 text(标准分词器会把 uuid 按连字符拆开),
  448. // term 拿整个 uuid 去比永远对不上,只能按短语匹配
  449. if (! empty($params['channel'])) {
  450. $filters[] = ['match_phrase' => ['metadata.channel' => $params['channel']]];
  451. }
  452. // ---------- 查询部分 ----------
  453. $queryText = trim($params['query'] ?? '');
  454. // fuzzy / definition 的巴利文多词查询按词的罕见度加权;其余模式不需要
  455. $weights = null;
  456. if ($queryText !== '' && ! in_array($mode, ['exact', 'semantic', 'hybrid'], true) && ! $this->isCjkQuery($queryText)) {
  457. $weights = $this->wordRarityWeights($this->scoringWords($this->splitQueryWords($queryText)));
  458. }
  459. if ($queryText === '') {
  460. $query = ['match_all' => new \stdClass];
  461. } else {
  462. switch ($mode) {
  463. case 'exact':
  464. $query = $this->buildExactQuery($queryText);
  465. break;
  466. case 'semantic':
  467. $query = $this->buildSemanticQuery($queryText);
  468. break;
  469. case 'hybrid':
  470. $query = $this->buildHybridQuery($queryText);
  471. break;
  472. case 'definition':
  473. $query = $this->buildDefinitionQuery($queryText, $weights);
  474. break;
  475. case 'fuzzy':
  476. default:
  477. $query = $this->buildFuzzyQuery($queryText, $weights);
  478. break;
  479. }
  480. }
  481. $highlightPreTags = $params['highlight_pre_tags'] ?? ['<mark>'];
  482. $highlightPostTags = $params['highlight_post_tags'] ?? ['</mark>'];
  483. // ---------- 最终 DSL ----------
  484. $dsl = [
  485. 'from' => $from,
  486. 'size' => $pageSize,
  487. '_source' => ['excludes' => $excludes],
  488. 'query' => ! empty($filters)
  489. ? [
  490. 'bool' => [
  491. 'must' => [$query],
  492. 'filter' => $filters,
  493. ],
  494. ]
  495. : $query,
  496. ];
  497. if ($params['aggregations'] ?? true) {
  498. $dsl['aggs'] = [
  499. 'resource_type' => [
  500. 'terms' => ['field' => 'resource_type'],
  501. ],
  502. 'language' => [
  503. 'terms' => ['field' => 'language'],
  504. ],
  505. 'category' => [
  506. 'terms' => ['field' => 'category'],
  507. ],
  508. 'granularity' => [
  509. 'terms' => ['field' => 'granularity'],
  510. ],
  511. ];
  512. }
  513. // 只有有搜索词时才开启高亮;字段按语种路由,避免把巴利文喂给中文分词器
  514. if ($queryText !== '') {
  515. $highlightFields = $this->isCjkQuery($queryText)
  516. ? ['title.text.zh', 'summary.text', 'content.text.zh']
  517. : ['title.text.pali', 'content.text.pali'];
  518. $dsl['highlight'] = [
  519. 'fields' => array_fill_keys($highlightFields, new \stdClass),
  520. 'fragmenter' => 'sentence',
  521. 'fragment_size' => 200,
  522. 'number_of_fragments' => 1,
  523. 'pre_tags' => $highlightPreTags,
  524. 'post_tags' => $highlightPostTags,
  525. ];
  526. }
  527. Log::debug(
  528. 'OpenSearchService::search',
  529. ['dsl' => json_encode($dsl, JSON_UNESCAPED_UNICODE)]
  530. );
  531. return $this->client->search([
  532. 'index' => config('mint.opensearch.index'),
  533. 'body' => $dsl,
  534. ]);
  535. }
  536. /**
  537. * 构建 exact(精确匹配)查询
  538. *
  539. * 使用 markdown_clean analyzer 的 exact subfield 进行匹配,
  540. * 适合巴利文词形精确检索场景。
  541. *
  542. * 查询字段:title.text.pali.exact, content.text.pali.exact, summary.text
  543. *
  544. * @param string $query 搜索关键词
  545. * @return array OpenSearch DSL query 片段
  546. */
  547. protected function buildExactQuery(string $query): array
  548. {
  549. return [
  550. 'multi_match' => [
  551. 'query' => $query,
  552. 'fields' => [
  553. 'title.text.pali.exact',
  554. 'content.text.pali.exact',
  555. 'summary.text',
  556. ],
  557. 'type' => 'best_fields',
  558. ],
  559. ];
  560. }
  561. /**
  562. * 构建 semantic(纯语义向量)查询
  563. *
  564. * 将查询文本通过 OpenAI embedding API 转为向量,
  565. * 同时对 content.vector、summary.vector、title.vector 三个 knn 字段检索,
  566. * 使用 bool should 合并结果。
  567. *
  568. * @param string $query 搜索关键词
  569. * @return array OpenSearch DSL query 片段
  570. *
  571. * @throws Exception embedding 调用失败时抛出
  572. */
  573. protected function buildSemanticQuery(string $query): array
  574. {
  575. $vector = $this->embedText($query);
  576. return [
  577. 'bool' => [
  578. 'should' => [
  579. ['knn' => ['content.vector' => ['vector' => $vector, 'k' => 20]]],
  580. ['knn' => ['summary.vector' => ['vector' => $vector, 'k' => 10]]],
  581. ['knn' => ['title.vector' => ['vector' => $vector, 'k' => 5]]],
  582. ],
  583. 'minimum_should_match' => 1,
  584. ],
  585. ];
  586. }
  587. /**
  588. * 构建 fuzzy(多字段模糊)查询
  589. *
  590. * 按查询语种路由字段,避免巴利文被中文分词器切碎、中文被巴利文 analyzer 误伤:
  591. * - 含汉字 → 只搜 bold_* + *.text.zh + summary.text
  592. * - 巴利文(拉丁字母)→ 走三层排序(见 buildPaliFuzzyQuery)+ bold_* 提权
  593. *
  594. * @param string $query 搜索关键词
  595. * @param array<string, float>|null $weights 巴利文各词的罕见度权重,null 表示都按 1
  596. * @return array OpenSearch DSL query 片段
  597. */
  598. protected function buildFuzzyQuery(string $query, ?array $weights = null): array
  599. {
  600. if ($this->isCjkQuery($query)) {
  601. return [
  602. 'multi_match' => [
  603. 'query' => $query,
  604. 'fields' => [
  605. 'bold_single^50',
  606. 'bold_multi^10',
  607. 'title.text.zh^3',
  608. 'summary.text^2',
  609. 'content.text.zh^1',
  610. ],
  611. 'type' => 'best_fields',
  612. ],
  613. ];
  614. }
  615. return $this->buildPaliFuzzyQuery($query, 1.0, $weights);
  616. }
  617. /**
  618. * 巴利文 fuzzy 的计分表(全部是固定分,逐项累加)
  619. *
  620. * 一个文档的得分 = 命中的每一项相加,于是「部分符合」自然逐级降分:
  621. * - phrase 整句按原顺序、拼写完全相同(≥2 个词才有)
  622. * - bigram 相邻两词按原顺序、拼写相同,每对一次(≥3 个词才有,2 个词时与 phrase 重合)
  623. * - exact 单个原始词拼写相同,每词一次
  624. * - synonym 单个原始词经同义词可替代,每词一次(拼写相同的词也会命中这一项)
  625. *
  626. * 以 3 个词为例:整句原样 66 > 全部拼写相同但乱序 36 > 两词相邻拼写相同 + 一词同义 31
  627. * > 两词拼写相同不相邻 24 > 三词全靠同义词 6 > 一词同义 2。
  628. *
  629. * @var array{phrase: int, bigram: int, exact: int, synonym: int}
  630. */
  631. private const PALI_FUZZY_SCORES = [
  632. 'phrase' => 20,
  633. 'bigram' => 5,
  634. 'exact' => 10,
  635. 'synonym' => 2,
  636. ];
  637. /**
  638. * definition 的计分表(黑体字部分,每个原始词各算一次)
  639. *
  640. * 主分不分词形:同义词词典的一行就是一个词的全部变格变位,所以「任一词形」走同义词,
  641. * 与 v2 search-pali-wbw 把全部词形一视同仁的口径一致;原拼写只给少量加分,排在同档前面。
  642. *
  643. * - single 该词(任一词形)是单独黑体字
  644. * - single_exact 再加:拼写也相同
  645. * - multi 该词(任一词形)出现在多词黑体短语里
  646. * - multi_exact 再加:拼写也相同
  647. * - multi_phrase 整句按原顺序、拼写相同出现在多词黑体短语里(≥2 个词才有)
  648. *
  649. * 每个词:单独黑体 ≥ 100 > 多词黑体 ≤ 35,于是命中的单独黑体字越多排越前。
  650. * 正文得分按 DEFINITION_TEXT_SCALE 缩小后叠加,只用来给黑体同分的文档排先后。
  651. *
  652. * @var array{single: int, single_exact: int, multi: int, multi_exact: int, multi_phrase: int}
  653. */
  654. private const DEFINITION_SCORES = [
  655. 'single' => 100,
  656. 'single_exact' => 10,
  657. 'multi' => 30,
  658. 'multi_exact' => 5,
  659. 'multi_phrase' => 30,
  660. ];
  661. /**
  662. * definition 模式里正文得分的缩放系数,保证正文再怎么命中也压不过一个黑体字
  663. */
  664. private const DEFINITION_TEXT_SCALE = 0.1;
  665. /**
  666. * 同分时的 BM25 微调权重:BM25 一般 < 30,乘上后 < 0.3,小于计分表的最小档差
  667. */
  668. private const TIE_BREAKER_BOOST = 0.01;
  669. /**
  670. * 罕见度权重的下限:再常见的词也保留这么多分量,不至于完全不计
  671. */
  672. private const RARITY_WEIGHT_FLOOR = 0.2;
  673. /**
  674. * 罕见度权重的指数:IDF 取了对数,887 段与 211 段的词只差 0.82 : 1,拉不开;
  675. * 归一后再取幂放大差距
  676. */
  677. private const RARITY_EXPONENT = 4;
  678. /**
  679. * 每个词的文档频率在 RedisCache 里的保存期(秒)。语料按月更新,一天足够新
  680. */
  681. private const DOC_FREQUENCY_TTL = 86400;
  682. /**
  683. * 多词查询里每个词的罕见度权重(类 BM25 的 IDF,按最罕见的词归一到 1)
  684. *
  685. * 按词计的固定分让每个词分量相同,常见词(如 bojjhaṅga,到处都是黑体)会把罕见的
  686. * 目标词(dhammavicayasambojjhaṅga)挤出前排。乘上这个权重后,越罕见的词分越高。
  687. * 文档频率按 title/content 的 .pali(带同义词,即全部词形)统计,一次 _msearch 取齐,
  688. * 逐词缓存。取不到时返回全 1(等于不加权),只记日志不报错。
  689. *
  690. * @param list<string> $words 参与计分的原始词(已去掉停用词)
  691. * @return array<string, float> 原始词 => 权重,范围 [RARITY_WEIGHT_FLOOR, 1]
  692. */
  693. protected function wordRarityWeights(array $words): array
  694. {
  695. $uniqueWords = array_values(array_unique($words));
  696. $flat = array_fill_keys($uniqueWords, 1.0);
  697. if (count($uniqueWords) < 2) {
  698. return $flat;
  699. }
  700. try {
  701. $index = config('mint.opensearch.index');
  702. $total = RedisCache::remember("/opensearch/{$index}/doc-count", self::DOC_FREQUENCY_TTL, fn () => $this->count());
  703. $frequencies = $this->documentFrequencies($index, $uniqueWords);
  704. } catch (Exception $e) {
  705. Log::warning('opensearch word rarity weights failed', ['words' => $uniqueWords, 'error' => $e->getMessage()]);
  706. return $flat;
  707. }
  708. $idf = [];
  709. foreach ($uniqueWords as $word) {
  710. $df = $frequencies[$word] ?? 0;
  711. $idf[$word] = log(1 + ($total - $df + 0.5) / ($df + 0.5));
  712. }
  713. $maxIdf = max($idf);
  714. if ($maxIdf <= 0) {
  715. return $flat;
  716. }
  717. return array_map(
  718. fn (float $value): float => max(self::RARITY_WEIGHT_FLOOR, ($value / $maxIdf) ** self::RARITY_EXPONENT),
  719. $idf,
  720. );
  721. }
  722. /**
  723. * 每个词出现在多少个文档里(含同义词展开的全部词形),逐词缓存,未缓存的一次 _msearch 取齐
  724. *
  725. * @param string $index 索引名
  726. * @param list<string> $words 原始词
  727. * @return array<string, int> 原始词 => 文档数
  728. */
  729. protected function documentFrequencies(string $index, array $words): array
  730. {
  731. $frequencies = [];
  732. $missing = [];
  733. foreach ($words as $word) {
  734. $cached = RedisCache::get($this->documentFrequencyCacheKey($index, $word));
  735. if ($cached === null) {
  736. $missing[] = $word;
  737. } else {
  738. $frequencies[$word] = (int) $cached;
  739. }
  740. }
  741. if ($missing === []) {
  742. return $frequencies;
  743. }
  744. $body = [];
  745. foreach ($missing as $word) {
  746. $body[] = ['index' => $index];
  747. $body[] = [
  748. 'size' => 0,
  749. 'track_total_hits' => true,
  750. 'query' => ['multi_match' => ['query' => $word, 'fields' => ['title.text.pali', 'content.text.pali']]],
  751. ];
  752. }
  753. $responses = $this->client->msearch(['body' => $body])['responses'] ?? [];
  754. foreach ($missing as $i => $word) {
  755. $df = (int) ($responses[$i]['hits']['total']['value'] ?? 0);
  756. $frequencies[$word] = $df;
  757. RedisCache::put($this->documentFrequencyCacheKey($index, $word), $df, self::DOC_FREQUENCY_TTL);
  758. }
  759. return $frequencies;
  760. }
  761. /**
  762. * @param string $index 索引名
  763. * @param string $word 原始词
  764. * @return string 文档频率的缓存 key
  765. */
  766. protected function documentFrequencyCacheKey(string $index, string $word): string
  767. {
  768. return "/opensearch/{$index}/word-df/".md5(mb_strtolower($word));
  769. }
  770. /**
  771. * 巴利文停用词(小写;比较前去掉标点)
  772. *
  773. * 取自 pg 全文检索的 pali.stop(api-v8/public/app/fts/pali.stop),另加 vā。
  774. * 停用词只参与词序打分(整句、相邻两词),不单独计分、不单独召回,见 buildPaliFuzzyQuery。
  775. *
  776. * @var list<string>
  777. */
  778. private const PALI_STOPWORDS = ['na', 'no', 'ca', 'va', 'vā', 'hi', 'pana', 'iva', 'eva'];
  779. /**
  780. * 判断原始词是否巴利文停用词
  781. *
  782. * @param string $word 原始词(可带标点,如「ca,」「‘‘na」)
  783. * @return bool 是停用词返回 true
  784. */
  785. protected function isPaliStopword(string $word): bool
  786. {
  787. $normalized = mb_strtolower(preg_replace('/[^\p{L}\p{M}]/u', '', $word) ?? '');
  788. return in_array($normalized, self::PALI_STOPWORDS, true);
  789. }
  790. /**
  791. * 取出用于单独计分的词:去掉停用词;全是停用词时原样返回,避免查不到东西
  792. *
  793. * @param list<string> $words 原始词
  794. * @return list<string>
  795. */
  796. protected function scoringWords(array $words): array
  797. {
  798. $contentWords = array_values(array_filter(
  799. $words,
  800. fn (string $word): bool => ! $this->isPaliStopword($word),
  801. ));
  802. return $contentWords === [] ? $words : $contentWords;
  803. }
  804. /**
  805. * 把查询切成原始词
  806. *
  807. * 按空白切分,并丢掉不含字母的片段(如「–」「.」):它们经分析器后没有 token,
  808. * 留着会让按词计分的子句永远不命中。
  809. *
  810. * @param string $query 搜索关键词
  811. * @return list<string>
  812. */
  813. protected function splitQueryWords(string $query): array
  814. {
  815. $words = preg_split('/\s+/u', trim($query)) ?: [];
  816. return array_values(array_filter(
  817. $words,
  818. fn (string $word): bool => preg_match('/\p{L}/u', $word) === 1,
  819. ));
  820. }
  821. /**
  822. * 包一层 constant_score:命中即得固定分,不受 BM25 字段长度归一化影响
  823. *
  824. * @param array<string, mixed> $filter 过滤子句
  825. * @param float $boost 命中时的固定分
  826. * @return array{constant_score: array{filter: array<string, mixed>, boost: float}}
  827. */
  828. protected function constantScore(array $filter, float $boost): array
  829. {
  830. return ['constant_score' => ['filter' => $filter, 'boost' => $boost]];
  831. }
  832. /**
  833. * 构建巴利文查询:词序符合、拼写相同得高分,部分符合逐级降分
  834. *
  835. * 命中按「原始词」(空格切分)计,不按同义词展开后的 token 计——每个原始词一个
  836. * constant_score 子句,命中几个同义词都只算一次。计分表见 PALI_FUZZY_SCORES。
  837. * 拼写相同打在 .exact 子字段(markdown_clean,无同义词),同义词打在 .pali。
  838. * 最后加一条极小权重的 BM25 子句,只用来给同分文档排先后。
  839. *
  840. * 停用词(PALI_STOPWORDS)只出现在整句、相邻两词的子句里,保住词序判断;
  841. * 不生成单词子句,也不进 BM25 子句,于是只命中「ca」的文档不会被召回。
  842. * 两个停用词组成的相邻词对同理跳过。查询全是停用词时按普通词处理。
  843. *
  844. * 单词子句(拼写、同义词)乘上该词的罕见度权重(见 wordRarityWeights),
  845. * 常见词分量小、罕见词分量大;词序子句(整句、相邻两词)不乘。
  846. *
  847. * @param string $query 搜索关键词
  848. * @param float $scale 整体缩放(definition 模式用它把正文得分压到黑体字之下)
  849. * @param array<string, float>|null $weights 原始词 => 罕见度权重,null 表示都按 1
  850. * @return array OpenSearch DSL query 片段
  851. */
  852. protected function buildPaliFuzzyQuery(string $query, float $scale = 1.0, ?array $weights = null): array
  853. {
  854. $words = $this->splitQueryWords($query);
  855. $wordCount = count($words);
  856. if ($wordCount === 0) {
  857. return ['match_all' => new \stdClass];
  858. }
  859. $scoringWords = $this->scoringWords($words);
  860. $allStopwords = array_all($words, fn (string $word): bool => $this->isPaliStopword($word));
  861. $exactFields = ['title.text.pali.exact', 'content.text.pali.exact'];
  862. $fuzzyFields = ['title.text.pali', 'content.text.pali'];
  863. $scores = array_map(fn (int $score): float => $score * $scale, self::PALI_FUZZY_SCORES);
  864. $should = [];
  865. // 词序:整句原样
  866. if ($wordCount >= 2) {
  867. $should[] = $this->constantScore([
  868. 'multi_match' => [
  869. 'query' => implode(' ', $words),
  870. 'type' => 'phrase',
  871. 'fields' => $exactFields,
  872. ],
  873. ], $scores['phrase']);
  874. }
  875. // 词序:相邻两词原样(部分顺序符合)
  876. if ($wordCount >= 3) {
  877. for ($i = 0; $i < $wordCount - 1; $i++) {
  878. $bothStopwords = $this->isPaliStopword($words[$i]) && $this->isPaliStopword($words[$i + 1]);
  879. if ($bothStopwords && ! $allStopwords) {
  880. continue;
  881. }
  882. $should[] = $this->constantScore([
  883. 'multi_match' => [
  884. 'query' => $words[$i].' '.$words[$i + 1],
  885. 'type' => 'phrase',
  886. 'fields' => $exactFields,
  887. ],
  888. ], $scores['bigram']);
  889. }
  890. }
  891. // 拼写:每个词各算一次(停用词不算),按罕见度加权
  892. foreach ($scoringWords as $word) {
  893. $weight = $weights[$word] ?? 1.0;
  894. $should[] = $this->constantScore([
  895. 'multi_match' => [
  896. 'query' => $word,
  897. 'fields' => $exactFields,
  898. 'operator' => 'and',
  899. ],
  900. ], $scores['exact'] * $weight);
  901. $should[] = $this->constantScore([
  902. 'multi_match' => [
  903. 'query' => $word,
  904. 'fields' => $fuzzyFields,
  905. ],
  906. ], $scores['synonym'] * $weight);
  907. }
  908. // 同分文档按 BM25 排先后
  909. $should[] = [
  910. 'match' => [
  911. 'content.text.pali' => [
  912. 'query' => implode(' ', $scoringWords),
  913. 'boost' => self::TIE_BREAKER_BOOST * $scale,
  914. ],
  915. ],
  916. ];
  917. return [
  918. 'bool' => [
  919. 'should' => $should,
  920. ],
  921. ];
  922. }
  923. /**
  924. * 判断查询是否含中文(CJK 统一表意文字)
  925. *
  926. * @param string $query 搜索关键词
  927. * @return bool 含汉字返回 true,否则按巴利文(拉丁字母)处理
  928. */
  929. protected function isCjkQuery(string $query): bool
  930. {
  931. return (bool) preg_match('/[\x{4E00}-\x{9FFF}\x{3400}-\x{4DBF}\x{F900}-\x{FAFF}]/u', $query);
  932. }
  933. /**
  934. * 构建 definition(定义查询)
  935. *
  936. * 义注里的黑体字通常就是被解释的词,所以黑体字命中决定排序,正文只做次级排序:
  937. * - 每个原始词单独算:命中的单独黑体字(bold_single)越多分越高
  938. * - 单独黑体字 > 多词黑体短语(bold_multi)里的词
  939. * - 词形不分高下(走同义词,即该词的全部变格变位),原拼写只在同档内加少量分:
  940. * bold_* 建索引用 standard,查询时显式指定 analyzer=standard 即是「拼写相同」,
  941. * 不指定则走带同义词的 pali_query_analyzer
  942. * - 多词黑体也按任一词形算:bold_* 取自 wbw_templates.real(已拆连音),
  943. * 正文里粘了连音(如 vitakkanti)匹配不到的词,往往靠它召回
  944. * - 用 match_phrase 而不是 match:中文在 standard 下按字切分,phrase 要求字连续,
  945. * 避免一个字重合就命中
  946. * - 每个词的黑体分乘上它的罕见度权重(见 wordRarityWeights):常见词(bojjhaṅga)
  947. * 不再与罕见的目标词(dhammavicayasambojjhaṅga)同分,挤占前排
  948. * 计分表见 DEFINITION_SCORES;正文部分复用 fuzzy 的计分,乘 DEFINITION_TEXT_SCALE。
  949. *
  950. * @param string $query 搜索关键词
  951. * @param array<string, float>|null $weights 原始词 => 罕见度权重,null 表示都按 1
  952. * @return array OpenSearch DSL query 片段
  953. */
  954. protected function buildDefinitionQuery(string $query, ?array $weights = null): array
  955. {
  956. $words = $this->splitQueryWords($query);
  957. if ($words === []) {
  958. return ['match_all' => new \stdClass];
  959. }
  960. $should = [];
  961. // 停用词不单独算黑体分(整句的 multi_phrase 仍带上它们)
  962. foreach ($this->scoringWords($words) as $word) {
  963. $weight = $weights[$word] ?? 1.0;
  964. foreach (['single' => 'bold_single', 'multi' => 'bold_multi'] as $tier => $field) {
  965. $should[] = $this->constantScore(
  966. ['match_phrase' => [$field => $word]],
  967. self::DEFINITION_SCORES[$tier] * $weight,
  968. );
  969. $should[] = $this->constantScore(
  970. ['match_phrase' => [$field => ['query' => $word, 'analyzer' => 'standard']]],
  971. self::DEFINITION_SCORES[$tier.'_exact'] * $weight,
  972. );
  973. }
  974. }
  975. if (count($words) >= 2) {
  976. $should[] = $this->constantScore(
  977. ['match_phrase' => ['bold_multi' => ['query' => implode(' ', $words), 'analyzer' => 'standard']]],
  978. self::DEFINITION_SCORES['multi_phrase'],
  979. );
  980. }
  981. // 正文:黑体同分时的次级排序,也保留没有黑体的文档(偈颂等)的召回
  982. if ($this->isCjkQuery($query)) {
  983. $should[] = [
  984. 'multi_match' => [
  985. 'query' => $query,
  986. 'fields' => ['title.text.zh^3', 'content.text.zh'],
  987. 'boost' => self::DEFINITION_TEXT_SCALE,
  988. ],
  989. ];
  990. } else {
  991. $should[] = $this->buildPaliFuzzyQuery($query, self::DEFINITION_TEXT_SCALE, $weights);
  992. }
  993. return [
  994. 'bool' => [
  995. 'should' => $should,
  996. ],
  997. ];
  998. }
  999. /**
  1000. * 构建 hybrid(模糊 + 语义混合)查询
  1001. *
  1002. * 使用 bool should 将 fuzzy(constant_score 包裹)与三路 knn 向量查询合并,
  1003. * 权重比例由 $weights['hybrid']['fuzzy_ratio'] 和 'semantic_ratio' 控制。
  1004. * title.vector 的语义权重略高(×1.2),以提升标题匹配的排名。
  1005. *
  1006. * @param string $query 搜索关键词
  1007. * @return array OpenSearch DSL query 片段
  1008. *
  1009. * @throws Exception embedding 调用失败时抛出
  1010. */
  1011. protected function buildHybridQuery(string $query): array
  1012. {
  1013. $fuzzyFields = [];
  1014. foreach ($this->weights['hybrid'] as $field => $weight) {
  1015. if (in_array($field, ['fuzzy_ratio', 'semantic_ratio'])) {
  1016. continue;
  1017. }
  1018. $fuzzyFields[] = $field.'^'.$weight;
  1019. }
  1020. $fuzzyPart = [
  1021. 'multi_match' => [
  1022. 'query' => $query,
  1023. 'fields' => $fuzzyFields,
  1024. 'type' => 'best_fields',
  1025. ],
  1026. ];
  1027. $vector = $this->embedText($query);
  1028. $fuzzyRatio = $this->weights['hybrid']['fuzzy_ratio'];
  1029. $semanticRatio = $this->weights['hybrid']['semantic_ratio'];
  1030. return [
  1031. 'bool' => [
  1032. 'should' => [
  1033. [
  1034. 'constant_score' => [
  1035. 'filter' => $fuzzyPart,
  1036. 'boost' => $fuzzyRatio,
  1037. ],
  1038. ],
  1039. [
  1040. 'knn' => [
  1041. 'content.vector' => [
  1042. 'vector' => $vector,
  1043. 'k' => 20,
  1044. 'boost' => $semanticRatio * 1.0,
  1045. ],
  1046. ],
  1047. ],
  1048. [
  1049. 'knn' => [
  1050. 'summary.vector' => [
  1051. 'vector' => $vector,
  1052. 'k' => 10,
  1053. 'boost' => $semanticRatio * 0.8,
  1054. ],
  1055. ],
  1056. ],
  1057. [
  1058. 'knn' => [
  1059. 'title.vector' => [
  1060. 'vector' => $vector,
  1061. 'k' => 5,
  1062. 'boost' => $semanticRatio * 1.2, // title 权重略高
  1063. ],
  1064. ],
  1065. ],
  1066. ],
  1067. ],
  1068. ];
  1069. }
  1070. /**
  1071. * 调用 OpenAI Embedding API 将文本转为向量
  1072. *
  1073. * 使用 Redis 缓存(TTL 7 天),相同文本不会重复请求 API,
  1074. * 缓存 key 格式见 embeddingCacheKey()。
  1075. *
  1076. * @param string $text 输入文本
  1077. * @return array 1536 维 float 向量
  1078. *
  1079. * @throws Exception 未设置 OPENAI_API_KEY 或 API 返回异常时抛出
  1080. */
  1081. protected function embedText(string $text): array
  1082. {
  1083. if (! $this->openaiApiKey) {
  1084. throw new Exception('请在 .env 设置 OPENAI_API_KEY');
  1085. }
  1086. return RedisCache::remember($this->embeddingCacheKey($text), now()->addDays(7), function () use ($text) {
  1087. $response = $this->http->post('embeddings', [
  1088. 'headers' => [
  1089. 'Authorization' => 'Bearer '.$this->openaiApiKey,
  1090. 'Content-Type' => 'application/json',
  1091. ],
  1092. 'json' => [
  1093. 'model' => 'text-embedding-3-small',
  1094. 'input' => $text,
  1095. ],
  1096. ]);
  1097. $json = json_decode((string) $response->getBody(), true);
  1098. if (empty($json['data'][0]['embedding'])) {
  1099. throw new Exception('OpenAI embedding 返回异常: '.json_encode($json));
  1100. }
  1101. return $json['data'][0]['embedding'];
  1102. });
  1103. }
  1104. /**
  1105. * embedding 缓存键:"embedding/v{版本}/{md5(text)}"。
  1106. *
  1107. * 版本号存在 EMBEDDING_CACHE_VERSION_KEY,clearAllEmbeddingCache() 把它加一,
  1108. * 旧版本的键就再也不会被读到,7 天后自然过期。原来用 Cache::tags(),
  1109. * tag 索引是另外的 key,在 Redis Cluster 上跨 slot。
  1110. */
  1111. private function embeddingCacheKey(string $text): string
  1112. {
  1113. $version = RedisCache::get(self::EMBEDDING_CACHE_VERSION_KEY, 0);
  1114. return "embedding/v{$version}/".md5($text);
  1115. }
  1116. /**
  1117. * 清除指定文本的 embedding 缓存
  1118. *
  1119. * @param string $text 原始文本(与调用 embedText 时一致)
  1120. * @return bool 缓存是否成功删除
  1121. *
  1122. * @example
  1123. * $service->clearEmbeddingCache('sabbe dhammā anattā');
  1124. */
  1125. public function clearEmbeddingCache(string $text): bool
  1126. {
  1127. return RedisCache::forget($this->embeddingCacheKey($text));
  1128. }
  1129. /**
  1130. * 让所有 embedding 缓存失效
  1131. *
  1132. * 不逐条删除,而是把版本号加一;旧键 7 天内自然过期。
  1133. *
  1134. * @example
  1135. * $service->clearAllEmbeddingCache();
  1136. */
  1137. public function clearAllEmbeddingCache(): void
  1138. {
  1139. RedisCache::increment(self::EMBEDDING_CACHE_VERSION_KEY);
  1140. }
  1141. /**
  1142. * 自动建议(Completion Suggest)
  1143. *
  1144. * 基于 completion 字段实现前缀补全,支持同时查询多个语言字段。
  1145. * 结果按 _score 降序排序,跨字段去重。
  1146. *
  1147. * 可用字段标识符($fields 参数):
  1148. * - 'title_pali' → title.suggest.pali
  1149. * - 'title_zh' → title.suggest.zh
  1150. * - 'content_pali' → content.suggest.pali
  1151. * - 'content_zh' → content.suggest.zh
  1152. *
  1153. * @param string $query 查询前缀文本
  1154. * @param array|string|null $fields 要查询的字段标识符,null 表示全部字段
  1155. * @param string|null $language 可选的语言过滤(term query)
  1156. * @param int $limit 每个字段返回的建议数量,默认 10
  1157. * @return array 建议结果列表,每项包含:
  1158. * text, source(字段标识符), score, doc_id, doc_source
  1159. *
  1160. * @throws \InvalidArgumentException $fields 中含无效字段标识符时抛出
  1161. *
  1162. * @example
  1163. * // 查询所有字段
  1164. * $service->suggest('nibb');
  1165. *
  1166. * // 只查询巴利文标题建议
  1167. * $service->suggest('nibb', 'title_pali');
  1168. *
  1169. * // 查询多个字段,限制语言
  1170. * $service->suggest('涅', ['title_zh', 'content_zh'], 'zh', 5);
  1171. */
  1172. public function suggest(
  1173. string $query,
  1174. $fields = null,
  1175. ?string $language = null,
  1176. int $limit = 10
  1177. ): array {
  1178. // 字段标识符 → OpenSearch completion 字段路径
  1179. $fieldMap = [
  1180. 'title_pali' => 'title.suggest.pali',
  1181. 'title_zh' => 'title.suggest.zh',
  1182. 'content_pali' => 'content.suggest.pali',
  1183. 'content_zh' => 'content.suggest.zh',
  1184. ];
  1185. // 处理字段参数
  1186. if ($fields === null) {
  1187. $searchFields = array_keys($fieldMap);
  1188. } elseif (is_string($fields)) {
  1189. $searchFields = [$fields];
  1190. } else {
  1191. $searchFields = $fields;
  1192. }
  1193. // 过滤无效字段
  1194. $searchFields = array_values(array_filter(
  1195. $searchFields,
  1196. fn ($field) => isset($fieldMap[$field])
  1197. ));
  1198. if (empty($searchFields)) {
  1199. throw new \InvalidArgumentException('Invalid fields specified for suggestion');
  1200. }
  1201. // 构建 suggest DSL
  1202. $suggests = [];
  1203. foreach ($searchFields as $field) {
  1204. $suggests[$field.'_suggest'] = [
  1205. 'prefix' => $query,
  1206. 'completion' => [
  1207. 'field' => $fieldMap[$field],
  1208. 'size' => $limit,
  1209. 'skip_duplicates' => true,
  1210. ],
  1211. ];
  1212. }
  1213. $dsl = ['suggest' => $suggests];
  1214. if ($language) {
  1215. $dsl['query'] = ['term' => ['language' => $language]];
  1216. }
  1217. $response = $this->client->search([
  1218. 'index' => config('mint.opensearch.index'),
  1219. 'body' => $dsl,
  1220. ]);
  1221. // 整理结果,附加来源字段
  1222. $results = [];
  1223. foreach ($searchFields as $field) {
  1224. $options = $response['suggest'][$field.'_suggest'][0]['options'] ?? [];
  1225. foreach ($options as $opt) {
  1226. $results[] = [
  1227. 'text' => $opt['text'] ?? '',
  1228. 'source' => $field,
  1229. 'score' => $opt['_score'] ?? 0,
  1230. 'doc_id' => $opt['_id'] ?? null,
  1231. 'doc_source' => $opt['_source'] ?? null,
  1232. ];
  1233. }
  1234. }
  1235. // 按分数降序排序
  1236. usort($results, fn ($a, $b) => $b['score'] <=> $a['score']);
  1237. return $results;
  1238. }
  1239. /**
  1240. * 按文档 ID 获取单条完整文档(包含 content.display)
  1241. *
  1242. * @param string $id 文档 ID,例如 "term_{guid}"
  1243. * @return array OpenSearch 原始响应
  1244. */
  1245. public function get(string $id): array
  1246. {
  1247. return $this->client->get([
  1248. 'index' => config('mint.opensearch.index'),
  1249. 'id' => $id,
  1250. ]);
  1251. }
  1252. /**
  1253. * 校验 pali_synonyms 同义词词典是否对指定词生效
  1254. *
  1255. * 通过 OpenSearch _analyze API,用当前索引的 pali_query_analyzer
  1256. * 对输入文本做实时分析,返回展开后的全部 token(含原词与同义词)。
  1257. * 可用于快速确认 analysis/pali_synonyms.txt 中的某一行是否已生效
  1258. * (例如 dhamma,dharma,法 => dhamma 是否真的展开出 dharma、法)。
  1259. *
  1260. * @param string $text 待检测的巴利词,例如 "dhamma"
  1261. * @return array<int, string> 分析器输出的 token 文本数组(已去重,保留原始顺序)
  1262. *
  1263. * @throws Exception 索引不存在或 OpenSearch 调用失败时抛出
  1264. *
  1265. * @example
  1266. * $service->pali_query_health_check('dhamma');
  1267. * // => ['dhamma', 'dharma', '法']
  1268. */
  1269. public function pali_query_health_check(string $text): array
  1270. {
  1271. $index = config('mint.opensearch.index');
  1272. if (! $this->client->indices()->exists(['index' => $index])) {
  1273. throw new Exception("Index [$index] does not exist.");
  1274. }
  1275. $response = $this->client->indices()->analyze([
  1276. 'index' => $index,
  1277. 'body' => [
  1278. 'analyzer' => 'pali_query_analyzer',
  1279. 'text' => $text,
  1280. ],
  1281. ]);
  1282. $tokens = array_map(
  1283. fn ($token) => $token['token'] ?? '',
  1284. $response['tokens'] ?? []
  1285. );
  1286. return array_values(array_unique(array_filter($tokens, fn ($t) => $t !== '')));
  1287. }
  1288. }