OpenSearchService.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. * 删除当前索引
  445. *
  446. * @return array OpenSearch 响应
  447. */
  448. public function deleteIndex(): array
  449. {
  450. $index = config('mint.opensearch.index');
  451. return $this->client->indices()->delete(['index' => $index]);
  452. }
  453. /**
  454. * 统计索引文档数量(支持可选条件过滤)
  455. *
  456. * @param array|null $query OpenSearch DSL query 子句,为 null 时统计全部文档。
  457. * 示例:['term' => ['language' => 'zh']]
  458. * ['exists' => ['field' => 'content.vector']]
  459. * @return int 文档总数
  460. *
  461. * @throws Exception
  462. *
  463. * @example
  464. * $service->count();
  465. * $service->count(['exists' => ['field' => 'content.vector']]);
  466. */
  467. public function count(?array $query = null): int
  468. {
  469. $index = config('mint.opensearch.index');
  470. $params = ['index' => $index];
  471. if (! empty($query)) {
  472. $params['body'] = ['query' => $query];
  473. }
  474. $response = $this->client->count($params);
  475. return (int) ($response['count'] ?? 0);
  476. }
  477. /**
  478. * 写入或覆盖单条文档
  479. *
  480. * @param string $id 文档 ID
  481. * @param array $body 文档内容,字段结构须与 mappings 一致
  482. * @return array OpenSearch 响应
  483. */
  484. public function create(string $id, array $body): array
  485. {
  486. return $this->client->index([
  487. 'index' => config('mint.opensearch.index'),
  488. 'id' => $id,
  489. 'body' => $body,
  490. ]);
  491. }
  492. /**
  493. * 删除单条文档
  494. *
  495. * @param string $id 文档 ID
  496. * @return array OpenSearch 响应
  497. */
  498. public function delete(string $id): array
  499. {
  500. return $this->client->delete([
  501. 'index' => config('mint.opensearch.index'),
  502. 'id' => $id,
  503. ]);
  504. }
  505. /**
  506. * 执行高级搜索
  507. *
  508. * 支持四种搜索模式:
  509. * - fuzzy 多字段模糊查询(默认),基于 BM25
  510. * - exact 精确匹配,使用 markdown_clean analyzer
  511. * - semantic 纯语义向量搜索,需要 OpenAI embedding
  512. * - hybrid fuzzy + semantic 混合,权重由 fuzzy_ratio / semantic_ratio 控制
  513. *
  514. * 支持的过滤参数:
  515. * resourceType, resourceId, granularity, language, category,
  516. * tags, pageRefs, relatedId, author, channel
  517. *
  518. * @param array $params {
  519. *
  520. * @type string $query 搜索关键词(必填)
  521. * @type string $searchMode 搜索模式,默认 'fuzzy'
  522. * @type int $page 页码,默认 1
  523. * @type int $pageSize 每页条数,默认 20
  524. * @type string $resourceType 按资源类型过滤
  525. * @type string $resourceId 按资源 ID 过滤
  526. * @type string $granularity 按粒度过滤
  527. * @type string $language 按语言过滤
  528. * @type string $category 按分类过滤
  529. * @type array $tags 按标签过滤(terms)
  530. * @type array $pageRefs 按页码引用过滤(terms)
  531. * @type string $relatedId 按关联 ID 过滤
  532. * @type string $author 按作者过滤
  533. * @type string $channel 按频道过滤
  534. * @type array $highlight_pre_tags 高亮前置标签,默认 ['<mark>']
  535. * @type array $highlight_post_tags 高亮后置标签,默认 ['</mark>']
  536. * }
  537. *
  538. * @return array OpenSearch 原始响应
  539. *
  540. * @throws Exception semantic / hybrid 模式下 embedding 调用失败时抛出
  541. */
  542. public function search(array $params): array
  543. {
  544. $page = $params['page'] ?? 1;
  545. $pageSize = $params['pageSize'] ?? 20;
  546. $from = ($page - 1) * $pageSize;
  547. $mode = $params['searchMode'] ?? 'fuzzy';
  548. // 排除字段
  549. if (! empty($params['excludes']) && is_array($params['excludes'])) {
  550. $excludes = array_merge($this->sourceExcludes, $params['excludes']);
  551. } else {
  552. $excludes = $this->sourceExcludes;
  553. }
  554. // ---------- 过滤条件 ----------
  555. $filters = [];
  556. if (! empty($params['resourceType'])) {
  557. $filters[] = ['term' => ['resource_type.keyword' => $params['resourceType']]];
  558. }
  559. if (! empty($params['resourceId'])) {
  560. $filters[] = ['term' => ['resource_id.keyword' => $params['resourceId']]];
  561. }
  562. if (! empty($params['granularity'])) {
  563. $filters[] = ['term' => ['granularity.keyword' => $params['granularity']]];
  564. }
  565. if (! empty($params['language'])) {
  566. $filters[] = ['term' => ['language.keyword' => $params['language']]];
  567. }
  568. if (! empty($params['category'])) {
  569. if (is_array($params['category'])) {
  570. $categories = $params['category'];
  571. } else {
  572. $categories = [$params['category']];
  573. }
  574. // 必须匹配全部:为每个 category 创建一个 term 条件
  575. foreach ($categories as $category) {
  576. $filters[] = ['term' => ['category.keyword' => $category]];
  577. }
  578. }
  579. if (! empty($params['tags'])) {
  580. $filters[] = ['terms' => ['tags' => $params['tags']]];
  581. }
  582. if (! empty($params['pageRefs'])) {
  583. $filters[] = ['terms' => ['page_refs' => $params['pageRefs']]];
  584. }
  585. if (! empty($params['relatedId'])) {
  586. $filters[] = ['term' => ['related_id' => $params['relatedId']]];
  587. }
  588. if (! empty($params['author'])) {
  589. $filters[] = ['match' => ['metadata.author' => $params['author']]];
  590. }
  591. if (! empty($params['channel'])) {
  592. $filters[] = ['term' => ['metadata.channel' => $params['channel']]];
  593. }
  594. // ---------- 查询部分 ----------
  595. $queryText = trim($params['query'] ?? '');
  596. if ($queryText === '') {
  597. $query = ['match_all' => new \stdClass];
  598. } else {
  599. switch ($mode) {
  600. case 'exact':
  601. $query = $this->buildExactQuery($queryText);
  602. break;
  603. case 'semantic':
  604. $query = $this->buildSemanticQuery($queryText);
  605. break;
  606. case 'hybrid':
  607. $query = $this->buildHybridQuery($queryText);
  608. break;
  609. case 'fuzzy':
  610. default:
  611. $query = $this->buildFuzzyQuery($queryText);
  612. break;
  613. }
  614. }
  615. $highlightPreTags = $params['highlight_pre_tags'] ?? ['<mark>'];
  616. $highlightPostTags = $params['highlight_post_tags'] ?? ['</mark>'];
  617. // ---------- 最终 DSL ----------
  618. $dsl = [
  619. 'from' => $from,
  620. 'size' => $pageSize,
  621. '_source' => ['excludes' => $excludes],
  622. 'query' => ! empty($filters)
  623. ? [
  624. 'bool' => [
  625. 'must' => [$query],
  626. 'filter' => $filters,
  627. ],
  628. ]
  629. : $query,
  630. 'aggs' => [
  631. 'resource_type' => [
  632. 'terms' => ['field' => 'resource_type.keyword'],
  633. ],
  634. 'language' => [
  635. 'terms' => ['field' => 'language.keyword'],
  636. ],
  637. 'category' => [
  638. 'terms' => ['field' => 'category.keyword'],
  639. ],
  640. 'granularity' => [
  641. 'terms' => ['field' => 'granularity.keyword'],
  642. ],
  643. ],
  644. ];
  645. // 只有有搜索词时才开启高亮
  646. if ($queryText !== '') {
  647. $dsl['highlight'] = [
  648. 'fields' => [
  649. 'title.text.pali' => new \stdClass,
  650. 'title.text.zh' => new \stdClass,
  651. 'summary.text' => new \stdClass,
  652. 'content.text.pali' => new \stdClass,
  653. 'content.text.zh' => new \stdClass,
  654. ],
  655. 'fragmenter' => 'sentence',
  656. 'fragment_size' => 200,
  657. 'number_of_fragments' => 1,
  658. 'pre_tags' => $highlightPreTags,
  659. 'post_tags' => $highlightPostTags,
  660. ];
  661. }
  662. Log::debug(
  663. 'OpenSearchService::search',
  664. ['dsl' => json_encode($dsl, JSON_UNESCAPED_UNICODE)]
  665. );
  666. return $this->client->search([
  667. 'index' => config('mint.opensearch.index'),
  668. 'body' => $dsl,
  669. ]);
  670. }
  671. /**
  672. * 构建 exact(精确匹配)查询
  673. *
  674. * 使用 markdown_clean analyzer 的 exact subfield 进行匹配,
  675. * 适合巴利文词形精确检索场景。
  676. *
  677. * 查询字段:title.text.pali.exact, content.text.pali.exact, summary.text
  678. *
  679. * @param string $query 搜索关键词
  680. * @return array OpenSearch DSL query 片段
  681. */
  682. protected function buildExactQuery(string $query): array
  683. {
  684. return [
  685. 'multi_match' => [
  686. 'query' => $query,
  687. 'fields' => [
  688. 'title.text.pali.exact',
  689. 'content.text.pali.exact',
  690. 'summary.text',
  691. ],
  692. 'type' => 'best_fields',
  693. ],
  694. ];
  695. }
  696. /**
  697. * 构建 semantic(纯语义向量)查询
  698. *
  699. * 将查询文本通过 OpenAI embedding API 转为向量,
  700. * 同时对 content.vector、summary.vector、title.vector 三个 knn 字段检索,
  701. * 使用 bool should 合并结果。
  702. *
  703. * @param string $query 搜索关键词
  704. * @return array OpenSearch DSL query 片段
  705. *
  706. * @throws Exception embedding 调用失败时抛出
  707. */
  708. protected function buildSemanticQuery(string $query): array
  709. {
  710. $vector = $this->embedText($query);
  711. return [
  712. 'bool' => [
  713. 'should' => [
  714. ['knn' => ['content.vector' => ['vector' => $vector, 'k' => 20]]],
  715. ['knn' => ['summary.vector' => ['vector' => $vector, 'k' => 10]]],
  716. ['knn' => ['title.vector' => ['vector' => $vector, 'k' => 5]]],
  717. ],
  718. 'minimum_should_match' => 1,
  719. ],
  720. ];
  721. }
  722. /**
  723. * 构建 fuzzy(多字段模糊)查询
  724. *
  725. * 基于 BM25 的 multi_match best_fields 查询,
  726. * 字段权重取自 $weights['fuzzy']。
  727. *
  728. * @param string $query 搜索关键词
  729. * @return array OpenSearch DSL query 片段
  730. */
  731. protected function buildFuzzyQuery(string $query): array
  732. {
  733. $fields = [];
  734. foreach ($this->weights['fuzzy'] as $field => $weight) {
  735. $fields[] = $field.'^'.$weight;
  736. }
  737. return [
  738. 'multi_match' => [
  739. 'query' => $query,
  740. 'fields' => $fields,
  741. 'type' => 'best_fields',
  742. ],
  743. ];
  744. }
  745. /**
  746. * 构建 hybrid(模糊 + 语义混合)查询
  747. *
  748. * 使用 bool should 将 fuzzy(constant_score 包裹)与三路 knn 向量查询合并,
  749. * 权重比例由 $weights['hybrid']['fuzzy_ratio'] 和 'semantic_ratio' 控制。
  750. * title.vector 的语义权重略高(×1.2),以提升标题匹配的排名。
  751. *
  752. * @param string $query 搜索关键词
  753. * @return array OpenSearch DSL query 片段
  754. *
  755. * @throws Exception embedding 调用失败时抛出
  756. */
  757. protected function buildHybridQuery(string $query): array
  758. {
  759. $fuzzyFields = [];
  760. foreach ($this->weights['hybrid'] as $field => $weight) {
  761. if (in_array($field, ['fuzzy_ratio', 'semantic_ratio'])) {
  762. continue;
  763. }
  764. $fuzzyFields[] = $field.'^'.$weight;
  765. }
  766. $fuzzyPart = [
  767. 'multi_match' => [
  768. 'query' => $query,
  769. 'fields' => $fuzzyFields,
  770. 'type' => 'best_fields',
  771. ],
  772. ];
  773. $vector = $this->embedText($query);
  774. $fuzzyRatio = $this->weights['hybrid']['fuzzy_ratio'];
  775. $semanticRatio = $this->weights['hybrid']['semantic_ratio'];
  776. return [
  777. 'bool' => [
  778. 'should' => [
  779. [
  780. 'constant_score' => [
  781. 'filter' => $fuzzyPart,
  782. 'boost' => $fuzzyRatio,
  783. ],
  784. ],
  785. [
  786. 'knn' => [
  787. 'content.vector' => [
  788. 'vector' => $vector,
  789. 'k' => 20,
  790. 'boost' => $semanticRatio * 1.0,
  791. ],
  792. ],
  793. ],
  794. [
  795. 'knn' => [
  796. 'summary.vector' => [
  797. 'vector' => $vector,
  798. 'k' => 10,
  799. 'boost' => $semanticRatio * 0.8,
  800. ],
  801. ],
  802. ],
  803. [
  804. 'knn' => [
  805. 'title.vector' => [
  806. 'vector' => $vector,
  807. 'k' => 5,
  808. 'boost' => $semanticRatio * 1.2, // title 权重略高
  809. ],
  810. ],
  811. ],
  812. ],
  813. ],
  814. ];
  815. }
  816. /**
  817. * 调用 OpenAI Embedding API 将文本转为向量
  818. *
  819. * 使用 Redis 缓存(TTL 7 天),相同文本不会重复请求 API,
  820. * 缓存 key 格式为 "embedding:{md5(text)}"。
  821. *
  822. * @param string $text 输入文本
  823. * @return array 1536 维 float 向量
  824. *
  825. * @throws Exception 未设置 OPENAI_API_KEY 或 API 返回异常时抛出
  826. */
  827. protected function embedText(string $text): array
  828. {
  829. if (! $this->openaiApiKey) {
  830. throw new Exception('请在 .env 设置 OPENAI_API_KEY');
  831. }
  832. $cacheKey = 'embedding:'.md5($text);
  833. return Cache::remember($cacheKey, now()->addDays(7), function () use ($text) {
  834. $response = $this->http->post('embeddings', [
  835. 'headers' => [
  836. 'Authorization' => 'Bearer '.$this->openaiApiKey,
  837. 'Content-Type' => 'application/json',
  838. ],
  839. 'json' => [
  840. 'model' => 'text-embedding-3-small',
  841. 'input' => $text,
  842. ],
  843. ]);
  844. $json = json_decode((string) $response->getBody(), true);
  845. if (empty($json['data'][0]['embedding'])) {
  846. throw new Exception('OpenAI embedding 返回异常: '.json_encode($json));
  847. }
  848. return $json['data'][0]['embedding'];
  849. });
  850. }
  851. /**
  852. * 清除指定文本的 embedding 缓存
  853. *
  854. * @param string $text 原始文本(与调用 embedText 时一致)
  855. * @return bool 缓存是否成功删除
  856. *
  857. * @example
  858. * $service->clearEmbeddingCache('sabbe dhammā anattā');
  859. */
  860. public function clearEmbeddingCache(string $text): bool
  861. {
  862. $cacheKey = 'embedding:'.md5($text);
  863. return Cache::forget($cacheKey);
  864. }
  865. /**
  866. * 清除 Redis 中所有 embedding 缓存
  867. *
  868. * 匹配 "embedding:*" 模式的全部键,生产环境请谨慎调用。
  869. *
  870. * @return int 已删除的缓存条数
  871. *
  872. * @example
  873. * $count = $service->clearAllEmbeddingCache();
  874. * echo "已清理缓存 {$count} 条";
  875. */
  876. public function clearAllEmbeddingCache(): int
  877. {
  878. $redis = Cache::getRedis();
  879. $keys = $redis->keys('embedding:*');
  880. if (! empty($keys)) {
  881. $redis->del($keys);
  882. }
  883. return count($keys);
  884. }
  885. /**
  886. * 自动建议(Completion Suggest)
  887. *
  888. * 基于 completion 字段实现前缀补全,支持同时查询多个语言字段。
  889. * 结果按 _score 降序排序,跨字段去重。
  890. *
  891. * 可用字段标识符($fields 参数):
  892. * - 'title_pali' → title.suggest.pali
  893. * - 'title_zh' → title.suggest.zh
  894. * - 'content_pali' → content.suggest.pali
  895. * - 'content_zh' → content.suggest.zh
  896. *
  897. * @param string $query 查询前缀文本
  898. * @param array|string|null $fields 要查询的字段标识符,null 表示全部字段
  899. * @param string|null $language 可选的语言过滤(term query)
  900. * @param int $limit 每个字段返回的建议数量,默认 10
  901. * @return array 建议结果列表,每项包含:
  902. * text, source(字段标识符), score, doc_id, doc_source
  903. *
  904. * @throws \InvalidArgumentException $fields 中含无效字段标识符时抛出
  905. *
  906. * @example
  907. * // 查询所有字段
  908. * $service->suggest('nibb');
  909. *
  910. * // 只查询巴利文标题建议
  911. * $service->suggest('nibb', 'title_pali');
  912. *
  913. * // 查询多个字段,限制语言
  914. * $service->suggest('涅', ['title_zh', 'content_zh'], 'zh', 5);
  915. */
  916. public function suggest(
  917. string $query,
  918. $fields = null,
  919. ?string $language = null,
  920. int $limit = 10
  921. ): array {
  922. // 字段标识符 → OpenSearch completion 字段路径
  923. $fieldMap = [
  924. 'title_pali' => 'title.suggest.pali',
  925. 'title_zh' => 'title.suggest.zh',
  926. 'content_pali' => 'content.suggest.pali',
  927. 'content_zh' => 'content.suggest.zh',
  928. ];
  929. // 处理字段参数
  930. if ($fields === null) {
  931. $searchFields = array_keys($fieldMap);
  932. } elseif (is_string($fields)) {
  933. $searchFields = [$fields];
  934. } else {
  935. $searchFields = $fields;
  936. }
  937. // 过滤无效字段
  938. $searchFields = array_values(array_filter(
  939. $searchFields,
  940. fn ($field) => isset($fieldMap[$field])
  941. ));
  942. if (empty($searchFields)) {
  943. throw new \InvalidArgumentException('Invalid fields specified for suggestion');
  944. }
  945. // 构建 suggest DSL
  946. $suggests = [];
  947. foreach ($searchFields as $field) {
  948. $suggests[$field.'_suggest'] = [
  949. 'prefix' => $query,
  950. 'completion' => [
  951. 'field' => $fieldMap[$field],
  952. 'size' => $limit,
  953. 'skip_duplicates' => true,
  954. ],
  955. ];
  956. }
  957. $dsl = ['suggest' => $suggests];
  958. if ($language) {
  959. $dsl['query'] = ['term' => ['language.keyword' => $language]];
  960. }
  961. $response = $this->client->search([
  962. 'index' => config('mint.opensearch.index'),
  963. 'body' => $dsl,
  964. ]);
  965. // 整理结果,附加来源字段
  966. $results = [];
  967. foreach ($searchFields as $field) {
  968. $options = $response['suggest'][$field.'_suggest'][0]['options'] ?? [];
  969. foreach ($options as $opt) {
  970. $results[] = [
  971. 'text' => $opt['text'] ?? '',
  972. 'source' => $field,
  973. 'score' => $opt['_score'] ?? 0,
  974. 'doc_id' => $opt['_id'] ?? null,
  975. 'doc_source' => $opt['_source'] ?? null,
  976. ];
  977. }
  978. }
  979. // 按分数降序排序
  980. usort($results, fn ($a, $b) => $b['score'] <=> $a['score']);
  981. return $results;
  982. }
  983. /**
  984. * 按文档 ID 获取单条完整文档(包含 content.display)
  985. *
  986. * @param string $id 文档 ID,例如 "term_{guid}"
  987. * @return array OpenSearch 原始响应
  988. */
  989. public function get(string $id): array
  990. {
  991. return $this->client->get([
  992. 'index' => config('mint.opensearch.index'),
  993. 'id' => $id,
  994. ]);
  995. }
  996. }