OpenSearchService.php 40 KB

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