OpenSearchService.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. <?php
  2. // api-v8/app/Services/OpenSearchService.php
  3. namespace App\Services;
  4. use Exception;
  5. use GuzzleHttp\Client;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Log;
  8. use OpenSearch\GuzzleClientFactory;
  9. class OpenSearchService
  10. {
  11. protected $client;
  12. protected $http;
  13. protected $openaiApiKey;
  14. /**
  15. * 默认查询排除字段
  16. *
  17. * @var array
  18. */
  19. private $sourceExcludes = [
  20. 'title.suggest.pali',
  21. 'title.suggest.zh',
  22. 'content.suggest.pali',
  23. 'content.suggest.zh',
  24. 'content.display', // 新增,列表页不返回 HTML
  25. ];
  26. /**
  27. * 默认权重配置
  28. *
  29. * fuzzy / hybrid 两种模式各自的字段权重。
  30. * hybrid 额外包含 fuzzy_ratio / semantic_ratio 用于控制两路得分的混合比例。
  31. *
  32. * 字段名已按新映射结构调整:
  33. * title.text.pali → 原 title.pali.text
  34. * title.text.zh → 原 title.zh
  35. * content.text.pali → 原 content.pali.text
  36. * content.text.zh → 原 content.zh
  37. *
  38. * @var array
  39. */
  40. private $weights = [
  41. 'fuzzy' => [
  42. 'bold_single' => 50,
  43. 'bold_multi' => 10,
  44. 'title.text.pali' => 3,
  45. 'title.text.zh' => 3,
  46. 'summary.text' => 2,
  47. 'content.text.pali' => 1,
  48. 'content.text.zh' => 1,
  49. ],
  50. 'hybrid' => [
  51. 'fuzzy_ratio' => 0.7,
  52. 'semantic_ratio' => 0.3,
  53. 'bold_single' => 50,
  54. 'bold_multi' => 10,
  55. 'title.text.pali' => 3,
  56. 'title.text.zh' => 3,
  57. 'summary.text' => 2,
  58. 'content.text.pali' => 1,
  59. 'content.text.zh' => 1,
  60. ],
  61. ];
  62. /**
  63. * OpenSearch 索引定义(settings + mappings)
  64. *
  65. * 字段结构说明:
  66. *
  67. * title
  68. * ├── text
  69. * │ ├── pali (text) 模糊查询 + exact subfield 精确查询
  70. * │ └── zh (text) 中文分词查询
  71. * ├── vector (knn_vector, dim=1536)
  72. * └── suggest
  73. * ├── pali (completion)
  74. * └── zh (completion)
  75. *
  76. * content(结构与 title 一致,额外包含 tokens nested 字段)
  77. * ├── text
  78. * │ ├── pali (text)
  79. * │ └── zh (text)
  80. * ├── tokens (nested)
  81. * ├── vector (knn_vector, dim=1536)
  82. * └── suggest
  83. * ├── pali (completion)
  84. * └── zh (completion)
  85. *
  86. * summary(中文摘要,结构保持不变)
  87. * ├── text (text)
  88. * └── vector (knn_vector, dim=1536)
  89. *
  90. * @var array
  91. */
  92. private $indexDefinition = [
  93. 'settings' => [
  94. 'index' => [
  95. 'knn' => true,
  96. ],
  97. 'analysis' => [
  98. 'analyzer' => [
  99. 'pali_query_analyzer' => [
  100. 'tokenizer' => 'standard',
  101. 'filter' => ['lowercase', 'pali_synonyms'],
  102. ],
  103. 'pali_index_analyzer' => [
  104. 'type' => 'custom',
  105. 'tokenizer' => 'standard',
  106. 'char_filter' => ['markdown_strip'],
  107. 'filter' => ['lowercase'],
  108. ],
  109. 'markdown_clean' => [
  110. 'type' => 'custom',
  111. 'tokenizer' => 'standard',
  112. 'char_filter' => ['markdown_strip'],
  113. 'filter' => ['lowercase'],
  114. ],
  115. // Suggest 专用(忽略大小写 + 变音)
  116. 'pali_suggest_analyzer' => [
  117. 'tokenizer' => 'standard',
  118. 'filter' => ['lowercase', 'asciifolding'],
  119. ],
  120. 'zh_suggest_analyzer' => [
  121. 'tokenizer' => 'ik_max_word',
  122. 'char_filter' => ['tsconvert'],
  123. ],
  124. // 中文简繁统一 (繁 -> 简)
  125. 'zh_index_analyzer' => [
  126. 'tokenizer' => 'ik_max_word',
  127. 'char_filter' => ['tsconvert'],
  128. ],
  129. 'zh_query_analyzer' => [
  130. 'tokenizer' => 'ik_smart',
  131. 'char_filter' => ['tsconvert'],
  132. ],
  133. ],
  134. 'filter' => [
  135. 'pali_synonyms' => [
  136. 'type' => 'synonym_graph',
  137. 'synonyms_path' => 'analysis/pali_synonyms.txt',
  138. 'updateable' => true,
  139. ],
  140. ],
  141. 'char_filter' => [
  142. 'markdown_strip' => [
  143. 'type' => 'pattern_replace',
  144. 'pattern' => '\\*\\*|\\*|_|`|~',
  145. 'replacement' => '',
  146. ],
  147. 'tsconvert' => [
  148. 'type' => 'stconvert',
  149. 'convert_type' => 't2s',
  150. ],
  151. ],
  152. ],
  153. ],
  154. 'mappings' => [
  155. 'properties' => [
  156. 'id' => ['type' => 'keyword'],
  157. 'resource_id' => ['type' => 'text', 'fields' => ['keyword' => ['type' => 'keyword', 'ignore_above' => 256]]],
  158. 'resource_type' => ['type' => 'text', 'fields' => ['keyword' => ['type' => 'keyword', 'ignore_above' => 256]]],
  159. // ----------------------------------------------------------------
  160. // title
  161. // text.pali → 模糊查询(+ exact subfield 精确查询)
  162. // text.zh → 中文查询
  163. // vector → 语义向量
  164. // suggest.pali / suggest.zh → 自动建议
  165. // ----------------------------------------------------------------
  166. 'title' => [
  167. 'properties' => [
  168. 'text' => [
  169. 'properties' => [
  170. 'pali' => [
  171. 'type' => 'text',
  172. 'analyzer' => 'pali_index_analyzer',
  173. 'search_analyzer' => 'pali_query_analyzer',
  174. 'fields' => [
  175. 'exact' => [
  176. 'type' => 'text',
  177. 'analyzer' => 'markdown_clean',
  178. ],
  179. ],
  180. ],
  181. 'zh' => [
  182. 'type' => 'text',
  183. 'analyzer' => 'zh_index_analyzer',
  184. 'search_analyzer' => 'zh_query_analyzer',
  185. ],
  186. ],
  187. ],
  188. 'vector' => [
  189. 'type' => 'knn_vector',
  190. 'dimension' => 1536,
  191. 'method' => [
  192. 'name' => 'hnsw',
  193. 'space_type' => 'innerproduct',
  194. 'engine' => 'faiss',
  195. ],
  196. ],
  197. 'suggest' => [
  198. 'properties' => [
  199. 'pali' => [
  200. 'type' => 'completion',
  201. 'analyzer' => 'pali_suggest_analyzer',
  202. ],
  203. 'zh' => [
  204. 'type' => 'completion',
  205. 'analyzer' => 'zh_suggest_analyzer',
  206. ],
  207. ],
  208. ],
  209. ],
  210. ],
  211. // ----------------------------------------------------------------
  212. // summary(LLM 生成的简体中文摘要,结构保持不变)
  213. // text → 中文查询
  214. // vector → 语义向量
  215. // ----------------------------------------------------------------
  216. 'summary' => [
  217. 'properties' => [
  218. 'text' => [
  219. 'type' => 'text',
  220. 'analyzer' => 'zh_index_analyzer',
  221. 'search_analyzer' => 'zh_query_analyzer',
  222. ],
  223. 'vector' => [
  224. 'type' => 'knn_vector',
  225. 'dimension' => 1536,
  226. 'method' => [
  227. 'name' => 'hnsw',
  228. 'space_type' => 'innerproduct',
  229. 'engine' => 'faiss',
  230. ],
  231. ],
  232. ],
  233. ],
  234. // ----------------------------------------------------------------
  235. // content(结构与 title 对称,额外包含 tokens nested 字段)
  236. // text.pali → 模糊查询(+ exact subfield 精确查询)
  237. // text.zh → 中文查询
  238. // tokens → 词法分析结果(nested)
  239. // vector → 语义向量
  240. // suggest.pali / suggest.zh → 自动建议
  241. // ----------------------------------------------------------------
  242. 'content' => [
  243. 'properties' => [
  244. 'text' => [
  245. 'properties' => [
  246. 'pali' => [
  247. 'type' => 'text',
  248. 'analyzer' => 'pali_index_analyzer',
  249. 'search_analyzer' => 'pali_query_analyzer',
  250. 'fields' => [
  251. 'exact' => [
  252. 'type' => 'text',
  253. 'analyzer' => 'markdown_clean',
  254. ],
  255. ],
  256. ],
  257. 'zh' => [
  258. 'type' => 'text',
  259. 'analyzer' => 'zh_index_analyzer',
  260. 'search_analyzer' => 'zh_query_analyzer',
  261. ],
  262. ],
  263. ],
  264. 'tokens' => [
  265. 'type' => 'nested',
  266. 'properties' => [
  267. 'surface' => ['type' => 'keyword'],
  268. 'lemma' => ['type' => 'keyword'],
  269. 'compound_parts' => ['type' => 'keyword'],
  270. 'case' => ['type' => 'keyword'],
  271. ],
  272. ],
  273. 'vector' => [
  274. 'type' => 'knn_vector',
  275. 'dimension' => 1536,
  276. 'method' => [
  277. 'name' => 'hnsw',
  278. 'space_type' => 'innerproduct',
  279. 'engine' => 'faiss',
  280. ],
  281. ],
  282. 'suggest' => [
  283. 'properties' => [
  284. 'pali' => [
  285. 'type' => 'completion',
  286. 'analyzer' => 'pali_suggest_analyzer',
  287. ],
  288. 'zh' => [
  289. 'type' => 'completion',
  290. 'analyzer' => 'zh_suggest_analyzer',
  291. ],
  292. ],
  293. ],
  294. // 前端展示用,原始 HTML,不参与索引
  295. 'display' => [
  296. 'type' => 'text',
  297. 'index' => false,
  298. ],
  299. ],
  300. ],
  301. 'related_id' => ['type' => 'keyword'],
  302. 'bold_single' => [
  303. 'type' => 'text',
  304. 'analyzer' => 'standard',
  305. 'search_analyzer' => 'pali_query_analyzer',
  306. ],
  307. 'bold_multi' => [
  308. 'type' => 'text',
  309. 'analyzer' => 'standard',
  310. 'search_analyzer' => 'pali_query_analyzer',
  311. ],
  312. 'path' => ['type' => 'text', 'analyzer' => 'standard'],
  313. 'page_refs' => ['type' => 'keyword'],
  314. 'tags' => ['type' => 'keyword'],
  315. 'category' => ['type' => 'text', 'fields' => ['keyword' => ['type' => 'keyword', 'ignore_above' => 256]]],
  316. 'author' => ['type' => 'text'],
  317. 'language' => ['type' => 'text', 'fields' => ['keyword' => ['type' => 'keyword', 'ignore_above' => 256]]],
  318. 'updated_at' => ['type' => 'date'],
  319. 'granularity' => ['type' => 'text', 'fields' => ['keyword' => ['type' => 'keyword', 'ignore_above' => 256]]],
  320. 'metadata' => [
  321. 'properties' => [
  322. 'APA' => ['type' => 'text', 'index' => false],
  323. 'MLA' => ['type' => 'text', 'index' => false],
  324. 'widget' => ['type' => 'text', 'index' => false],
  325. 'author' => ['type' => 'text'],
  326. 'channel' => ['type' => 'text'],
  327. ],
  328. ],
  329. ],
  330. ],
  331. ];
  332. /**
  333. * 创建 OpenSearchService 实例
  334. *
  335. * 从 config('mint.opensearch.config') 读取连接配置,
  336. * 同时初始化 OpenAI HTTP 客户端用于 embedding 调用。
  337. */
  338. public function __construct()
  339. {
  340. $config = config('mint.opensearch.config');
  341. $hostUrl = "{$config['scheme']}://{$config['host']}:{$config['port']}";
  342. $this->client = (new GuzzleClientFactory)->create([
  343. 'base_uri' => $hostUrl,
  344. 'auth' => [$config['username'], $config['password']],
  345. 'verify' => $config['ssl_verification'],
  346. ]);
  347. $this->openaiApiKey = env('OPENAI_API_KEY');
  348. $this->http = new Client([
  349. 'base_uri' => 'https://api.openai.com/v1/',
  350. 'timeout' => 15,
  351. ]);
  352. }
  353. /**
  354. * 动态覆盖指定搜索模式的字段权重
  355. *
  356. * @param string $mode 搜索模式,支持 'fuzzy' | 'hybrid'
  357. * @param array $weights 需要覆盖的权重键值对,例如:['title.text.pali' => 5]
  358. */
  359. public function setWeights(string $mode, array $weights): void
  360. {
  361. if (isset($this->weights[$mode])) {
  362. $this->weights[$mode] = array_merge($this->weights[$mode], $weights);
  363. }
  364. }
  365. /**
  366. * 测试与 OpenSearch 集群的连接状态
  367. *
  368. * @return array{0: bool, 1: string} [连接是否成功, 描述信息]
  369. */
  370. public function testConnection(): array
  371. {
  372. try {
  373. $info = $this->client->info();
  374. $message = 'OpenSearch 连接成功: '.json_encode($info['version']['number']);
  375. Log::info($message);
  376. return [true, $message];
  377. } catch (Exception $e) {
  378. $message = 'OpenSearch 连接失败: '.$e->getMessage();
  379. Log::error($message);
  380. return [false, $message];
  381. }
  382. }
  383. /**
  384. * 检查当前索引是否已存在
  385. */
  386. public function indexExists(): bool
  387. {
  388. $index = config('mint.opensearch.index');
  389. return $this->client->indices()->exists(['index' => $index]);
  390. }
  391. /**
  392. * 创建 OpenSearch 索引
  393. *
  394. * 使用 $indexDefinition 中定义的 settings 和 mappings 创建索引。
  395. * 若索引已存在则抛出异常,避免覆盖生产数据。
  396. *
  397. * @return array OpenSearch 响应
  398. *
  399. * @throws Exception 索引已存在时抛出
  400. */
  401. public function createIndex(): array
  402. {
  403. $index = config('mint.opensearch.index');
  404. $exists = $this->client->indices()->exists(['index' => $index]);
  405. if ($exists) {
  406. throw new Exception("Index [$index] already exists.");
  407. }
  408. return $this->client->indices()->create([
  409. 'index' => $index,
  410. 'body' => $this->indexDefinition,
  411. ]);
  412. }
  413. /**
  414. * 更新已有索引的 settings 和 mappings
  415. *
  416. * 更新 settings 时会临时关闭索引(close → putSettings → open),
  417. * 更新 mappings 支持热更新(新增字段),不可修改已有字段类型。
  418. *
  419. * @return array 包含 'settings' 和/或 'mappings' 的响应数组
  420. */
  421. public function updateIndex(): array
  422. {
  423. $index = config('mint.opensearch.index');
  424. $settings = $this->indexDefinition['settings'] ?? [];
  425. $mappings = $this->indexDefinition['mappings'] ?? [];
  426. $response = [];
  427. if (! empty($settings)) {
  428. $this->client->indices()->close(['index' => $index]);
  429. $response['settings'] = $this->client->indices()->putSettings([
  430. 'index' => $index,
  431. 'body' => ['settings' => $settings],
  432. ]);
  433. $this->client->indices()->open(['index' => $index]);
  434. }
  435. if (! empty($mappings)) {
  436. $response['mappings'] = $this->client->indices()->putMapping([
  437. 'index' => $index,
  438. 'body' => $mappings,
  439. ]);
  440. }
  441. return $response;
  442. }
  443. /**
  444. * 切换 pali 同义词文件版本
  445. *
  446. * 把 pali_synonyms filter 的 synonyms_path 指向
  447. * analysis/pali-synonyms-{$version}.txt(文件须已存在于 OpenSearch
  448. * 各节点的 config 目录中,否则索引无法重新打开)。
  449. *
  450. * synonyms_path 属于静态 settings,必须 close → putSettings → open。
  451. * 无论 putSettings 成功与否都会尝试重新打开索引,避免索引停留在 close 状态。
  452. *
  453. * @param string $version 版本号,仅允许 [A-Za-z0-9._-]
  454. * @return array{path: string, settings: array} 新路径与 OpenSearch 响应
  455. *
  456. * @throws Exception 版本号非法、索引不存在或 OpenSearch 拒绝时抛出
  457. *
  458. * @example
  459. * $service->updatePaliSynonymsPath('20260731');
  460. */
  461. public function updatePaliSynonymsPath(string $version): array
  462. {
  463. if (! preg_match('/^[A-Za-z0-9._-]+$/', $version)) {
  464. throw new Exception("Invalid synonyms version [$version].");
  465. }
  466. $index = config('mint.opensearch.index');
  467. if (! $this->client->indices()->exists(['index' => $index])) {
  468. throw new Exception("Index [$index] does not exist.");
  469. }
  470. $path = "analysis/pali-synonyms-{$version}.txt";
  471. // 以代码中的 analysis 定义为准,只替换同义词文件路径
  472. $analysis = $this->indexDefinition['settings']['analysis'];
  473. $analysis['filter']['pali_synonyms']['synonyms_path'] = $path;
  474. $this->client->indices()->close(['index' => $index]);
  475. try {
  476. $response = $this->client->indices()->putSettings([
  477. 'index' => $index,
  478. 'body' => ['settings' => ['analysis' => $analysis]],
  479. ]);
  480. } finally {
  481. $this->client->indices()->open(['index' => $index]);
  482. }
  483. Log::info('OpenSearchService::updatePaliSynonymsPath', [
  484. 'index' => $index,
  485. 'synonyms_path' => $path,
  486. ]);
  487. return ['path' => $path, 'settings' => $response];
  488. }
  489. /**
  490. * 读取当前索引使用的 pali 同义词文件路径
  491. *
  492. * @return string|null 形如 "analysis/pali-synonyms-20260731.txt",未设置时返回 null
  493. */
  494. public function getPaliSynonymsPath(): ?string
  495. {
  496. return $this->getPaliSynonymsSetting()['synonyms_path'] ?? null;
  497. }
  498. /**
  499. * 读取当前索引 pali_synonyms filter 的完整设置
  500. *
  501. * @return array{type?: string, synonyms_path?: string, updateable?: string}|null 未设置时返回 null
  502. */
  503. public function getPaliSynonymsSetting(): ?array
  504. {
  505. $index = config('mint.opensearch.index');
  506. $settings = $this->client->indices()->getSettings(['index' => $index]);
  507. return $settings[$index]['settings']['index']['analysis']['filter']['pali_synonyms'] ?? null;
  508. }
  509. /**
  510. * 删除当前索引
  511. *
  512. * @return array OpenSearch 响应
  513. */
  514. public function deleteIndex(): array
  515. {
  516. $index = config('mint.opensearch.index');
  517. return $this->client->indices()->delete(['index' => $index]);
  518. }
  519. /**
  520. * 统计索引文档数量(支持可选条件过滤)
  521. *
  522. * @param array|null $query OpenSearch DSL query 子句,为 null 时统计全部文档。
  523. * 示例:['term' => ['language' => 'zh']]
  524. * ['exists' => ['field' => 'content.vector']]
  525. * @return int 文档总数
  526. *
  527. * @throws Exception
  528. *
  529. * @example
  530. * $service->count();
  531. * $service->count(['exists' => ['field' => 'content.vector']]);
  532. */
  533. public function count(?array $query = null): int
  534. {
  535. $index = config('mint.opensearch.index');
  536. $params = ['index' => $index];
  537. if (! empty($query)) {
  538. $params['body'] = ['query' => $query];
  539. }
  540. $response = $this->client->count($params);
  541. return (int) ($response['count'] ?? 0);
  542. }
  543. /**
  544. * 写入或覆盖单条文档
  545. *
  546. * @param string $id 文档 ID
  547. * @param array $body 文档内容,字段结构须与 mappings 一致
  548. * @return array OpenSearch 响应
  549. */
  550. public function create(string $id, array $body): array
  551. {
  552. return $this->client->index([
  553. 'index' => config('mint.opensearch.index'),
  554. 'id' => $id,
  555. 'body' => $body,
  556. ]);
  557. }
  558. /**
  559. * 删除单条文档
  560. *
  561. * @param string $id 文档 ID
  562. * @return array OpenSearch 响应
  563. */
  564. public function delete(string $id): array
  565. {
  566. return $this->client->delete([
  567. 'index' => config('mint.opensearch.index'),
  568. 'id' => $id,
  569. ]);
  570. }
  571. /**
  572. * 执行高级搜索
  573. *
  574. * 支持四种搜索模式:
  575. * - fuzzy 多字段模糊查询(默认),基于 BM25
  576. * - exact 精确匹配,使用 markdown_clean analyzer
  577. * - semantic 纯语义向量搜索,需要 OpenAI embedding
  578. * - hybrid fuzzy + semantic 混合,权重由 fuzzy_ratio / semantic_ratio 控制
  579. *
  580. * 支持的过滤参数:
  581. * resourceType, resourceId, granularity, language, category,
  582. * tags, pageRefs, relatedId, author, channel
  583. *
  584. * @param array $params {
  585. *
  586. * @type string $query 搜索关键词(必填)
  587. * @type string $searchMode 搜索模式,默认 'fuzzy'
  588. * @type int $page 页码,默认 1
  589. * @type int $pageSize 每页条数,默认 20
  590. * @type string $resourceType 按资源类型过滤
  591. * @type string $resourceId 按资源 ID 过滤
  592. * @type string $granularity 按粒度过滤
  593. * @type string $language 按语言过滤
  594. * @type string $category 按分类过滤
  595. * @type array $tags 按标签过滤(terms)
  596. * @type array $pageRefs 按页码引用过滤(terms)
  597. * @type string $relatedId 按关联 ID 过滤
  598. * @type string $author 按作者过滤
  599. * @type string $channel 按频道过滤
  600. * @type array $highlight_pre_tags 高亮前置标签,默认 ['<mark>']
  601. * @type array $highlight_post_tags 高亮后置标签,默认 ['</mark>']
  602. * }
  603. *
  604. * @return array OpenSearch 原始响应
  605. *
  606. * @throws Exception semantic / hybrid 模式下 embedding 调用失败时抛出
  607. */
  608. public function search(array $params): array
  609. {
  610. $page = $params['page'] ?? 1;
  611. $pageSize = $params['pageSize'] ?? 20;
  612. $from = ($page - 1) * $pageSize;
  613. $mode = $params['searchMode'] ?? 'fuzzy';
  614. // 排除字段
  615. if (! empty($params['excludes']) && is_array($params['excludes'])) {
  616. $excludes = array_merge($this->sourceExcludes, $params['excludes']);
  617. } else {
  618. $excludes = $this->sourceExcludes;
  619. }
  620. // ---------- 过滤条件 ----------
  621. $filters = [];
  622. if (! empty($params['resourceType'])) {
  623. $filters[] = ['term' => ['resource_type.keyword' => $params['resourceType']]];
  624. }
  625. if (! empty($params['resourceId'])) {
  626. $filters[] = ['term' => ['resource_id.keyword' => $params['resourceId']]];
  627. }
  628. if (! empty($params['granularity'])) {
  629. $filters[] = ['term' => ['granularity.keyword' => $params['granularity']]];
  630. }
  631. if (! empty($params['language'])) {
  632. $filters[] = ['term' => ['language.keyword' => $params['language']]];
  633. }
  634. if (! empty($params['category'])) {
  635. if (is_array($params['category'])) {
  636. $categories = $params['category'];
  637. } else {
  638. $categories = [$params['category']];
  639. }
  640. // 必须匹配全部:为每个 category 创建一个 term 条件
  641. foreach ($categories as $category) {
  642. $filters[] = ['term' => ['category.keyword' => $category]];
  643. }
  644. }
  645. if (! empty($params['tags'])) {
  646. $filters[] = ['terms' => ['tags' => $params['tags']]];
  647. }
  648. if (! empty($params['pageRefs'])) {
  649. $filters[] = ['terms' => ['page_refs' => $params['pageRefs']]];
  650. }
  651. if (! empty($params['relatedId'])) {
  652. $filters[] = ['term' => ['related_id' => $params['relatedId']]];
  653. }
  654. if (! empty($params['author'])) {
  655. $filters[] = ['match' => ['metadata.author' => $params['author']]];
  656. }
  657. if (! empty($params['channel'])) {
  658. $filters[] = ['term' => ['metadata.channel' => $params['channel']]];
  659. }
  660. // ---------- 查询部分 ----------
  661. $queryText = trim($params['query'] ?? '');
  662. if ($queryText === '') {
  663. $query = ['match_all' => new \stdClass];
  664. } else {
  665. switch ($mode) {
  666. case 'exact':
  667. $query = $this->buildExactQuery($queryText);
  668. break;
  669. case 'semantic':
  670. $query = $this->buildSemanticQuery($queryText);
  671. break;
  672. case 'hybrid':
  673. $query = $this->buildHybridQuery($queryText);
  674. break;
  675. case 'fuzzy':
  676. default:
  677. $query = $this->buildFuzzyQuery($queryText);
  678. break;
  679. }
  680. }
  681. $highlightPreTags = $params['highlight_pre_tags'] ?? ['<mark>'];
  682. $highlightPostTags = $params['highlight_post_tags'] ?? ['</mark>'];
  683. // ---------- 最终 DSL ----------
  684. $dsl = [
  685. 'from' => $from,
  686. 'size' => $pageSize,
  687. '_source' => ['excludes' => $excludes],
  688. 'query' => ! empty($filters)
  689. ? [
  690. 'bool' => [
  691. 'must' => [$query],
  692. 'filter' => $filters,
  693. ],
  694. ]
  695. : $query,
  696. 'aggs' => [
  697. 'resource_type' => [
  698. 'terms' => ['field' => 'resource_type.keyword'],
  699. ],
  700. 'language' => [
  701. 'terms' => ['field' => 'language.keyword'],
  702. ],
  703. 'category' => [
  704. 'terms' => ['field' => 'category.keyword'],
  705. ],
  706. 'granularity' => [
  707. 'terms' => ['field' => 'granularity.keyword'],
  708. ],
  709. ],
  710. ];
  711. // 只有有搜索词时才开启高亮
  712. if ($queryText !== '') {
  713. $dsl['highlight'] = [
  714. 'fields' => [
  715. 'title.text.pali' => new \stdClass,
  716. 'title.text.zh' => new \stdClass,
  717. 'summary.text' => new \stdClass,
  718. 'content.text.pali' => new \stdClass,
  719. 'content.text.zh' => new \stdClass,
  720. ],
  721. 'fragmenter' => 'sentence',
  722. 'fragment_size' => 200,
  723. 'number_of_fragments' => 1,
  724. 'pre_tags' => $highlightPreTags,
  725. 'post_tags' => $highlightPostTags,
  726. ];
  727. }
  728. Log::debug(
  729. 'OpenSearchService::search',
  730. ['dsl' => json_encode($dsl, JSON_UNESCAPED_UNICODE)]
  731. );
  732. return $this->client->search([
  733. 'index' => config('mint.opensearch.index'),
  734. 'body' => $dsl,
  735. ]);
  736. }
  737. /**
  738. * 构建 exact(精确匹配)查询
  739. *
  740. * 使用 markdown_clean analyzer 的 exact subfield 进行匹配,
  741. * 适合巴利文词形精确检索场景。
  742. *
  743. * 查询字段:title.text.pali.exact, content.text.pali.exact, summary.text
  744. *
  745. * @param string $query 搜索关键词
  746. * @return array OpenSearch DSL query 片段
  747. */
  748. protected function buildExactQuery(string $query): array
  749. {
  750. return [
  751. 'multi_match' => [
  752. 'query' => $query,
  753. 'fields' => [
  754. 'title.text.pali.exact',
  755. 'content.text.pali.exact',
  756. 'summary.text',
  757. ],
  758. 'type' => 'best_fields',
  759. ],
  760. ];
  761. }
  762. /**
  763. * 构建 semantic(纯语义向量)查询
  764. *
  765. * 将查询文本通过 OpenAI embedding API 转为向量,
  766. * 同时对 content.vector、summary.vector、title.vector 三个 knn 字段检索,
  767. * 使用 bool should 合并结果。
  768. *
  769. * @param string $query 搜索关键词
  770. * @return array OpenSearch DSL query 片段
  771. *
  772. * @throws Exception embedding 调用失败时抛出
  773. */
  774. protected function buildSemanticQuery(string $query): array
  775. {
  776. $vector = $this->embedText($query);
  777. return [
  778. 'bool' => [
  779. 'should' => [
  780. ['knn' => ['content.vector' => ['vector' => $vector, 'k' => 20]]],
  781. ['knn' => ['summary.vector' => ['vector' => $vector, 'k' => 10]]],
  782. ['knn' => ['title.vector' => ['vector' => $vector, 'k' => 5]]],
  783. ],
  784. 'minimum_should_match' => 1,
  785. ],
  786. ];
  787. }
  788. /**
  789. * 构建 fuzzy(多字段模糊)查询
  790. *
  791. * 基于 BM25 的 multi_match best_fields 查询,
  792. * 字段权重取自 $weights['fuzzy']。
  793. *
  794. * @param string $query 搜索关键词
  795. * @return array OpenSearch DSL query 片段
  796. */
  797. protected function buildFuzzyQuery(string $query): array
  798. {
  799. $fields = [];
  800. foreach ($this->weights['fuzzy'] as $field => $weight) {
  801. $fields[] = $field.'^'.$weight;
  802. }
  803. return [
  804. 'multi_match' => [
  805. 'query' => $query,
  806. 'fields' => $fields,
  807. 'type' => 'best_fields',
  808. ],
  809. ];
  810. }
  811. /**
  812. * 构建 hybrid(模糊 + 语义混合)查询
  813. *
  814. * 使用 bool should 将 fuzzy(constant_score 包裹)与三路 knn 向量查询合并,
  815. * 权重比例由 $weights['hybrid']['fuzzy_ratio'] 和 'semantic_ratio' 控制。
  816. * title.vector 的语义权重略高(×1.2),以提升标题匹配的排名。
  817. *
  818. * @param string $query 搜索关键词
  819. * @return array OpenSearch DSL query 片段
  820. *
  821. * @throws Exception embedding 调用失败时抛出
  822. */
  823. protected function buildHybridQuery(string $query): array
  824. {
  825. $fuzzyFields = [];
  826. foreach ($this->weights['hybrid'] as $field => $weight) {
  827. if (in_array($field, ['fuzzy_ratio', 'semantic_ratio'])) {
  828. continue;
  829. }
  830. $fuzzyFields[] = $field.'^'.$weight;
  831. }
  832. $fuzzyPart = [
  833. 'multi_match' => [
  834. 'query' => $query,
  835. 'fields' => $fuzzyFields,
  836. 'type' => 'best_fields',
  837. ],
  838. ];
  839. $vector = $this->embedText($query);
  840. $fuzzyRatio = $this->weights['hybrid']['fuzzy_ratio'];
  841. $semanticRatio = $this->weights['hybrid']['semantic_ratio'];
  842. return [
  843. 'bool' => [
  844. 'should' => [
  845. [
  846. 'constant_score' => [
  847. 'filter' => $fuzzyPart,
  848. 'boost' => $fuzzyRatio,
  849. ],
  850. ],
  851. [
  852. 'knn' => [
  853. 'content.vector' => [
  854. 'vector' => $vector,
  855. 'k' => 20,
  856. 'boost' => $semanticRatio * 1.0,
  857. ],
  858. ],
  859. ],
  860. [
  861. 'knn' => [
  862. 'summary.vector' => [
  863. 'vector' => $vector,
  864. 'k' => 10,
  865. 'boost' => $semanticRatio * 0.8,
  866. ],
  867. ],
  868. ],
  869. [
  870. 'knn' => [
  871. 'title.vector' => [
  872. 'vector' => $vector,
  873. 'k' => 5,
  874. 'boost' => $semanticRatio * 1.2, // title 权重略高
  875. ],
  876. ],
  877. ],
  878. ],
  879. ],
  880. ];
  881. }
  882. /**
  883. * 调用 OpenAI Embedding API 将文本转为向量
  884. *
  885. * 使用 Redis 缓存(TTL 7 天),相同文本不会重复请求 API,
  886. * 缓存 key 格式为 "embedding:{md5(text)}"。
  887. *
  888. * @param string $text 输入文本
  889. * @return array 1536 维 float 向量
  890. *
  891. * @throws Exception 未设置 OPENAI_API_KEY 或 API 返回异常时抛出
  892. */
  893. protected function embedText(string $text): array
  894. {
  895. if (! $this->openaiApiKey) {
  896. throw new Exception('请在 .env 设置 OPENAI_API_KEY');
  897. }
  898. $cacheKey = 'embedding:'.md5($text);
  899. return Cache::remember($cacheKey, now()->addDays(7), function () use ($text) {
  900. $response = $this->http->post('embeddings', [
  901. 'headers' => [
  902. 'Authorization' => 'Bearer '.$this->openaiApiKey,
  903. 'Content-Type' => 'application/json',
  904. ],
  905. 'json' => [
  906. 'model' => 'text-embedding-3-small',
  907. 'input' => $text,
  908. ],
  909. ]);
  910. $json = json_decode((string) $response->getBody(), true);
  911. if (empty($json['data'][0]['embedding'])) {
  912. throw new Exception('OpenAI embedding 返回异常: '.json_encode($json));
  913. }
  914. return $json['data'][0]['embedding'];
  915. });
  916. }
  917. /**
  918. * 清除指定文本的 embedding 缓存
  919. *
  920. * @param string $text 原始文本(与调用 embedText 时一致)
  921. * @return bool 缓存是否成功删除
  922. *
  923. * @example
  924. * $service->clearEmbeddingCache('sabbe dhammā anattā');
  925. */
  926. public function clearEmbeddingCache(string $text): bool
  927. {
  928. $cacheKey = 'embedding:'.md5($text);
  929. return Cache::forget($cacheKey);
  930. }
  931. /**
  932. * 清除 Redis 中所有 embedding 缓存
  933. *
  934. * 匹配 "embedding:*" 模式的全部键,生产环境请谨慎调用。
  935. *
  936. * @return int 已删除的缓存条数
  937. *
  938. * @example
  939. * $count = $service->clearAllEmbeddingCache();
  940. * echo "已清理缓存 {$count} 条";
  941. */
  942. public function clearAllEmbeddingCache(): int
  943. {
  944. $redis = Cache::getRedis();
  945. $keys = $redis->keys('embedding:*');
  946. if (! empty($keys)) {
  947. $redis->del($keys);
  948. }
  949. return count($keys);
  950. }
  951. /**
  952. * 自动建议(Completion Suggest)
  953. *
  954. * 基于 completion 字段实现前缀补全,支持同时查询多个语言字段。
  955. * 结果按 _score 降序排序,跨字段去重。
  956. *
  957. * 可用字段标识符($fields 参数):
  958. * - 'title_pali' → title.suggest.pali
  959. * - 'title_zh' → title.suggest.zh
  960. * - 'content_pali' → content.suggest.pali
  961. * - 'content_zh' → content.suggest.zh
  962. *
  963. * @param string $query 查询前缀文本
  964. * @param array|string|null $fields 要查询的字段标识符,null 表示全部字段
  965. * @param string|null $language 可选的语言过滤(term query)
  966. * @param int $limit 每个字段返回的建议数量,默认 10
  967. * @return array 建议结果列表,每项包含:
  968. * text, source(字段标识符), score, doc_id, doc_source
  969. *
  970. * @throws \InvalidArgumentException $fields 中含无效字段标识符时抛出
  971. *
  972. * @example
  973. * // 查询所有字段
  974. * $service->suggest('nibb');
  975. *
  976. * // 只查询巴利文标题建议
  977. * $service->suggest('nibb', 'title_pali');
  978. *
  979. * // 查询多个字段,限制语言
  980. * $service->suggest('涅', ['title_zh', 'content_zh'], 'zh', 5);
  981. */
  982. public function suggest(
  983. string $query,
  984. $fields = null,
  985. ?string $language = null,
  986. int $limit = 10
  987. ): array {
  988. // 字段标识符 → OpenSearch completion 字段路径
  989. $fieldMap = [
  990. 'title_pali' => 'title.suggest.pali',
  991. 'title_zh' => 'title.suggest.zh',
  992. 'content_pali' => 'content.suggest.pali',
  993. 'content_zh' => 'content.suggest.zh',
  994. ];
  995. // 处理字段参数
  996. if ($fields === null) {
  997. $searchFields = array_keys($fieldMap);
  998. } elseif (is_string($fields)) {
  999. $searchFields = [$fields];
  1000. } else {
  1001. $searchFields = $fields;
  1002. }
  1003. // 过滤无效字段
  1004. $searchFields = array_values(array_filter(
  1005. $searchFields,
  1006. fn ($field) => isset($fieldMap[$field])
  1007. ));
  1008. if (empty($searchFields)) {
  1009. throw new \InvalidArgumentException('Invalid fields specified for suggestion');
  1010. }
  1011. // 构建 suggest DSL
  1012. $suggests = [];
  1013. foreach ($searchFields as $field) {
  1014. $suggests[$field.'_suggest'] = [
  1015. 'prefix' => $query,
  1016. 'completion' => [
  1017. 'field' => $fieldMap[$field],
  1018. 'size' => $limit,
  1019. 'skip_duplicates' => true,
  1020. ],
  1021. ];
  1022. }
  1023. $dsl = ['suggest' => $suggests];
  1024. if ($language) {
  1025. $dsl['query'] = ['term' => ['language.keyword' => $language]];
  1026. }
  1027. $response = $this->client->search([
  1028. 'index' => config('mint.opensearch.index'),
  1029. 'body' => $dsl,
  1030. ]);
  1031. // 整理结果,附加来源字段
  1032. $results = [];
  1033. foreach ($searchFields as $field) {
  1034. $options = $response['suggest'][$field.'_suggest'][0]['options'] ?? [];
  1035. foreach ($options as $opt) {
  1036. $results[] = [
  1037. 'text' => $opt['text'] ?? '',
  1038. 'source' => $field,
  1039. 'score' => $opt['_score'] ?? 0,
  1040. 'doc_id' => $opt['_id'] ?? null,
  1041. 'doc_source' => $opt['_source'] ?? null,
  1042. ];
  1043. }
  1044. }
  1045. // 按分数降序排序
  1046. usort($results, fn ($a, $b) => $b['score'] <=> $a['score']);
  1047. return $results;
  1048. }
  1049. /**
  1050. * 按文档 ID 获取单条完整文档(包含 content.display)
  1051. *
  1052. * @param string $id 文档 ID,例如 "term_{guid}"
  1053. * @return array OpenSearch 原始响应
  1054. */
  1055. public function get(string $id): array
  1056. {
  1057. return $this->client->get([
  1058. 'index' => config('mint.opensearch.index'),
  1059. 'id' => $id,
  1060. ]);
  1061. }
  1062. }