OpenSearchService.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  1. <?php
  2. // api-v8/app/Services/OpenSearchService.php
  3. namespace App\Services;
  4. use OpenSearch\GuzzleClientFactory;
  5. use Illuminate\Support\Facades\Log;
  6. use GuzzleHttp\Client;
  7. use Illuminate\Support\Facades\Cache;
  8. use Exception;
  9. class OpenSearchService
  10. {
  11. protected $client;
  12. protected $http;
  13. protected $openaiApiKey;
  14. /** 默认查询排除字段 **/
  15. private $sourceExcludes = [
  16. 'title.suggest',
  17. 'content.suggest',
  18. ];
  19. /** 默认权重配置 **/
  20. private $weights = [
  21. 'fuzzy' => [
  22. 'bold_single' => 50,
  23. 'bold_multi' => 10,
  24. 'title.pali.text' => 3,
  25. 'title.zh' => 3,
  26. 'summary.text' => 2,
  27. 'content.pali.text' => 1,
  28. 'content.zh' => 1,
  29. ],
  30. 'hybrid' => [
  31. 'fuzzy_ratio' => 0.7,
  32. 'semantic_ratio' => 0.3,
  33. 'bold_single' => 50,
  34. 'bold_multi' => 10,
  35. 'title.pali.text' => 3,
  36. 'title.zh' => 3,
  37. 'summary.text' => 2,
  38. 'content.pali.text' => 1,
  39. 'content.zh' => 1,
  40. ],
  41. ];
  42. private $indexDefinition = [
  43. 'settings' => [
  44. 'index' => [
  45. 'knn' => true,
  46. ],
  47. 'analysis' => [
  48. 'analyzer' => [
  49. /** */
  50. 'pali_query_analyzer' => [
  51. 'tokenizer' => 'standard',
  52. 'filter' => ['lowercase', 'pali_synonyms'],
  53. ],
  54. 'pali_index_analyzer' => [
  55. 'type' => 'custom',
  56. 'tokenizer' => 'standard',
  57. 'char_filter' => ['markdown_strip'],
  58. 'filter' => ['lowercase'],
  59. ],
  60. 'markdown_clean' => [
  61. 'type' => 'custom',
  62. 'tokenizer' => 'standard',
  63. 'char_filter' => ['markdown_strip'],
  64. 'filter' => ['lowercase'],
  65. ],
  66. // Suggest 专用(忽略大小写 + 变音)
  67. 'pali_suggest_analyzer' => [
  68. 'tokenizer' => 'standard',
  69. 'filter' => ['lowercase', 'asciifolding']
  70. ],
  71. // 中文简繁统一 (繁 -> 简)
  72. 'zh_index_analyzer' => [
  73. 'tokenizer' => 'ik_max_word',
  74. 'char_filter' => ['tsconvert'],
  75. ],
  76. 'zh_query_analyzer' => [
  77. 'tokenizer' => 'ik_smart',
  78. 'char_filter' => ['tsconvert'],
  79. ]
  80. ],
  81. 'filter' => [
  82. 'pali_synonyms' => [
  83. 'type' => 'synonym_graph',
  84. 'synonyms_path' => 'analysis/pali_synonyms.txt',
  85. 'updateable' => true,
  86. ],
  87. ],
  88. 'char_filter' => [
  89. 'markdown_strip' => [
  90. 'type' => 'pattern_replace',
  91. 'pattern' => '\\*\\*|\\*|_|`|~',
  92. 'replacement' => '',
  93. ],
  94. "tsconvert" => [
  95. "type" => "stconvert",
  96. "convert_type" => "t2s"
  97. ]
  98. ],
  99. ],
  100. ],
  101. 'mappings' => [
  102. 'properties' => [
  103. 'id' => ['type' => 'keyword'],
  104. 'resource_id' => ['type' => 'keyword'],
  105. 'resource_type' => ['type' => 'keyword'],
  106. 'title' => [
  107. 'properties' => [
  108. 'pali' => [
  109. 'type' => 'text',
  110. 'fields' => [
  111. /**模糊查询 */
  112. 'text' => [
  113. 'type' => 'text',
  114. 'analyzer' => 'pali_index_analyzer',
  115. 'search_analyzer' => 'pali_query_analyzer',
  116. ],
  117. /**准确查询 */
  118. 'exact' => [
  119. 'type' => 'text',
  120. 'analyzer' => 'markdown_clean',
  121. ],
  122. ],
  123. ],
  124. 'zh' => [
  125. 'type' => 'text',
  126. 'analyzer' => 'zh_index_analyzer',
  127. 'search_analyzer' => 'zh_query_analyzer',
  128. ],
  129. 'vector' => [
  130. 'type' => 'knn_vector',
  131. 'dimension' => 1536,
  132. 'method' => [
  133. 'name' => 'hnsw',
  134. 'space_type' => 'cosinesimil',
  135. 'engine' => 'nmslib',
  136. ],
  137. ],
  138. // 自动建议字段
  139. 'suggest' => [
  140. 'type' => 'completion',
  141. 'analyzer' => 'pali_suggest_analyzer'
  142. ],
  143. ],
  144. ],
  145. /** 简体中文 llm生成 */
  146. 'summary' => [
  147. 'properties' => [
  148. 'text' => [
  149. 'type' => 'text',
  150. 'analyzer' => 'zh_index_analyzer',
  151. 'search_analyzer' => 'zh_query_analyzer',
  152. ],
  153. 'vector' => [
  154. 'type' => 'knn_vector',
  155. 'dimension' => 1536,
  156. 'method' => [
  157. 'name' => 'hnsw',
  158. 'space_type' => 'cosinesimil',
  159. 'engine' => 'nmslib',
  160. ],
  161. ],
  162. ]
  163. ],
  164. 'content' => [
  165. 'properties' => [
  166. 'pali' => [
  167. 'type' => 'text',
  168. 'fields' => [
  169. /**模糊查询 */
  170. 'text' => [
  171. 'type' => 'text',
  172. 'analyzer' => 'pali_index_analyzer',
  173. 'search_analyzer' => 'pali_query_analyzer',
  174. ],
  175. /**准确查询 */
  176. 'exact' => [
  177. 'type' => 'text',
  178. 'analyzer' => 'markdown_clean',
  179. ],
  180. ],
  181. ],
  182. 'zh' => [
  183. 'type' => 'text',
  184. 'analyzer' => 'zh_index_analyzer',
  185. 'search_analyzer' => 'zh_query_analyzer',
  186. ],
  187. 'tokens' => [
  188. 'type' => 'nested',
  189. 'properties' => [
  190. 'surface' => ['type' => 'keyword'],
  191. 'lemma' => ['type' => 'keyword'],
  192. 'compound_parts' => ['type' => 'keyword'],
  193. 'case' => ['type' => 'keyword'],
  194. ],
  195. ],
  196. 'vector' => [
  197. 'type' => 'knn_vector',
  198. 'dimension' => 1536,
  199. 'method' => [
  200. 'name' => 'hnsw',
  201. 'space_type' => 'cosinesimil',
  202. 'engine' => 'nmslib',
  203. ],
  204. ],
  205. 'suggest' => [
  206. 'type' => 'completion',
  207. 'analyzer' => 'pali_suggest_analyzer'
  208. ]
  209. ],
  210. ],
  211. 'related_id' => ['type' => 'keyword'],
  212. 'bold_single' => [
  213. 'type' => 'text',
  214. 'analyzer' => 'standard',
  215. 'search_analyzer' => 'pali_query_analyzer',
  216. ],
  217. 'bold_multi' => [
  218. 'type' => 'text',
  219. 'analyzer' => 'standard',
  220. 'search_analyzer' => 'pali_query_analyzer',
  221. ],
  222. 'path' => ['type' => 'text', 'analyzer' => 'standard'],
  223. 'page_refs' => [
  224. 'type' => 'keyword',
  225. ],
  226. 'tags' => ['type' => 'keyword'],
  227. 'category' => ['type' => 'keyword'],
  228. 'author' => ['type' => 'text'],
  229. 'language' => ['type' => 'keyword'],
  230. 'updated_at' => ['type' => 'date'],
  231. 'granularity' => ['type' => 'keyword'],
  232. 'metadata' => [
  233. 'properties' => [
  234. 'APA' => ['type' => 'text', 'index' => false],
  235. 'MLA' => ['type' => 'text', 'index' => false],
  236. 'widget' => ['type' => 'text', 'index' => false],
  237. 'author' => ['type' => 'text'], //
  238. 'channel' => ['type' => 'text'], //
  239. ],
  240. ],
  241. ],
  242. ],
  243. ];
  244. public function __construct()
  245. {
  246. $config = config('mint.opensearch.config');
  247. $hostUrl = "{$config['scheme']}://{$config['host']}:{$config['port']}";
  248. $this->client = (new GuzzleClientFactory())->create([
  249. 'base_uri' => $hostUrl,
  250. 'auth' => [$config['username'], $config['password']],
  251. 'verify' => $config['ssl_verification'],
  252. ]);
  253. $this->openaiApiKey = env('OPENAI_API_KEY');
  254. $this->http = new Client([
  255. 'base_uri' => 'https://api.openai.com/v1/',
  256. 'timeout' => 15,
  257. ]);
  258. }
  259. public function setWeights(string $mode, array $weights)
  260. {
  261. if (isset($this->weights[$mode])) {
  262. $this->weights[$mode] = array_merge($this->weights[$mode], $weights);
  263. }
  264. }
  265. public function testConnection()
  266. {
  267. try {
  268. $info = $this->client->info();
  269. $message = 'OpenSearch 连接成功: ' . json_encode($info['version']['number']);
  270. Log::info($message);
  271. return [true, $message];
  272. } catch (\Exception $e) {
  273. $message = 'OpenSearch 连接失败: ' . $e->getMessage();
  274. Log::error($message);
  275. return [false, $message];
  276. }
  277. }
  278. public function indexExists()
  279. {
  280. $index = config('mint.opensearch.index');
  281. return $this->client->indices()->exists(['index' => $index]);
  282. }
  283. /** 索引管理方法保持不变... **/
  284. public function createIndex()
  285. {
  286. $index = config('mint.opensearch.index');
  287. $exists = $this->client->indices()->exists(['index' => $index]);
  288. if ($exists) {
  289. throw new \Exception("Index [$index] already exists.");
  290. }
  291. return $this->client->indices()->create([
  292. 'index' => $index,
  293. 'body' => $this->indexDefinition
  294. ]);
  295. }
  296. public function updateIndex()
  297. {
  298. $index = config('mint.opensearch.index');
  299. $settings = $this->indexDefinition['settings'] ?? [];
  300. $mappings = $this->indexDefinition['mappings'] ?? [];
  301. $response = [];
  302. if (!empty($settings)) {
  303. $this->client->indices()->close(['index' => $index]);
  304. $response['settings'] = $this->client->indices()->putSettings([
  305. 'index' => $index,
  306. 'body' => ['settings' => $settings]
  307. ]);
  308. $this->client->indices()->open(['index' => $index]);
  309. }
  310. if (!empty($mappings)) {
  311. $response['mappings'] = $this->client->indices()->putMapping([
  312. 'index' => $index,
  313. 'body' => $mappings
  314. ]);
  315. }
  316. return $response;
  317. }
  318. public function deleteIndex()
  319. {
  320. $index = config('mint.opensearch.index');
  321. return $this->client->indices()->delete(['index' => $index]);
  322. }
  323. /**
  324. * 获取索引文档数量(支持条件统计)
  325. *
  326. * @param array|null $query 可选的查询条件(OpenSearch DSL query 部分)
  327. * 例如:
  328. * [
  329. * 'term' => ['language' => 'zh']
  330. * ]
  331. *
  332. * @return int 文档总数
  333. *
  334. * @throws \Exception
  335. *
  336. * @example
  337. * // 获取索引全部文档数量
  338. * $count = $service->count();
  339. *
  340. * // 按条件统计(例如:只统计有 embedding 的文档)
  341. * $count = $service->count([
  342. * 'exists' => ['field' => 'content.vector']
  343. * ]);
  344. */
  345. public function count(?array $query = null): int
  346. {
  347. $index = config('mint.opensearch.index');
  348. $params = [
  349. 'index' => $index,
  350. ];
  351. // 如果传入 query,则按条件统计
  352. if (!empty($query)) {
  353. $params['body'] = [
  354. 'query' => $query
  355. ];
  356. }
  357. $response = $this->client->count($params);
  358. return (int) ($response['count'] ?? 0);
  359. }
  360. public function create(string $id, array $body)
  361. {
  362. return $this->client->index([
  363. 'index' => config('mint.opensearch.index'),
  364. 'id' => $id,
  365. 'body' => $body
  366. ]);
  367. }
  368. public function delete($id)
  369. {
  370. return $this->client->delete(['index' => config('mint.opensearch.index'), 'id' => $id]);
  371. }
  372. /**
  373. * 执行高级搜索(支持 fuzzy / exact / semantic / hybrid 四种模式)
  374. *
  375. * @param array $params 搜索参数数组
  376. * - query: 搜索关键词
  377. * - searchMode: 搜索模式 (fuzzy|exact|semantic|hybrid)
  378. * - page: 页码,默认 1
  379. * - pageSize: 每页条数,默认 20
  380. * - resourceType / language / category / tags / relatedId / pageRefs / author / channel 等过滤条件
  381. * @return array OpenSearch 返回的搜索结果
  382. *
  383. * @throws \Exception
  384. */
  385. public function search(array $params)
  386. {
  387. // 分页参数
  388. $page = $params['page'] ?? 1;
  389. $pageSize = $params['pageSize'] ?? 20;
  390. $from = ($page - 1) * $pageSize;
  391. // 搜索模式,默认 fuzzy
  392. $mode = $params['searchMode'] ?? 'fuzzy';
  393. // ---------- 过滤条件 ----------
  394. $filters = [];
  395. if (!empty($params['resourceType'])) {
  396. $filters[] = ['term' => ['resource_type' => $params['resourceType']]];
  397. }
  398. if (!empty($params['resourceId'])) {
  399. $filters[] = ['term' => ['resource_id' => $params['resourceId']]];
  400. }
  401. if (!empty($params['granularity'])) {
  402. $filters[] = ['term' => ['granularity' => $params['granularity']]];
  403. }
  404. if (!empty($params['language'])) {
  405. $filters[] = ['term' => ['language' => $params['language']]];
  406. }
  407. if (!empty($params['category'])) {
  408. $filters[] = ['term' => ['category' => $params['category']]];
  409. }
  410. if (!empty($params['tags'])) {
  411. $filters[] = ['terms' => ['tags' => $params['tags']]];
  412. }
  413. if (!empty($params['pageRefs'])) {
  414. $filters[] = ['terms' => ['page_refs' => $params['pageRefs']]];
  415. }
  416. if (!empty($params['relatedId'])) {
  417. $filters[] = ['term' => ['related_id' => $params['relatedId']]];
  418. }
  419. if (!empty($params['author'])) {
  420. $filters[] = ['match' => ['metadata.author' => $params['author']]];
  421. }
  422. if (!empty($params['channel'])) {
  423. $filters[] = ['term' => ['metadata.channel' => $params['channel']]];
  424. }
  425. // ---------- 查询部分 ----------
  426. switch ($mode) {
  427. case 'exact':
  428. $query = $this->buildExactQuery($params['query']);
  429. break;
  430. case 'semantic':
  431. $query = $this->buildSemanticQuery($params['query']);
  432. break;
  433. case 'hybrid':
  434. $query = $this->buildHybridQuery($params['query']);
  435. break;
  436. case 'fuzzy':
  437. default:
  438. $query = $this->buildFuzzyQuery($params['query']);
  439. }
  440. if (!empty($params['highlight_pre_tags'])) {
  441. $highlight_pre_tags = $params['highlight_pre_tags'];
  442. } else {
  443. $highlight_pre_tags = ['<mark>'];
  444. }
  445. if (!empty($params['highlight_post_tags'])) {
  446. $highlight_post_tags = $params['highlight_post_tags'];
  447. } else {
  448. $highlight_post_tags = ['</mark>'];
  449. }
  450. // ---------- 最终 DSL ----------
  451. $dsl = [
  452. 'from' => $from,
  453. 'size' => $pageSize,
  454. '_source' => [
  455. 'excludes' => $this->sourceExcludes
  456. ],
  457. 'query' => !empty($filters)
  458. ? ['bool' => ['must' => [$query], 'filter' => $filters]]
  459. : $query,
  460. 'aggs' => [
  461. 'resource_type' => ['terms' => ['field' => 'resource_type']],
  462. 'language' => ['terms' => ['field' => 'language']],
  463. 'category' => ['terms' => ['field' => 'category']],
  464. 'granularity' => ['terms' => ['field' => 'granularity']],
  465. ],
  466. 'highlight' => [
  467. 'fields' => [
  468. 'title.pali.text' => new \stdClass(),
  469. 'title.zh' => new \stdClass(),
  470. 'summary.text' => new \stdClass(),
  471. 'content.pali.text' => new \stdClass(),
  472. 'content.zh' => new \stdClass(),
  473. ],
  474. "fragmenter" => "sentence",
  475. "fragment_size" => 200,
  476. "number_of_fragments" => 1,
  477. 'pre_tags' => $highlight_pre_tags,
  478. 'post_tags' => $highlight_post_tags,
  479. ],
  480. ];
  481. Log::debug('search', ['dsl' => json_encode($dsl, JSON_UNESCAPED_UNICODE)]);
  482. // ---------- 执行查询 ----------
  483. $response = $this->client->search([
  484. 'index' => config('mint.opensearch.index'),
  485. 'body' => $dsl
  486. ]);
  487. return $response;
  488. }
  489. /**
  490. * 构建 exact 查询
  491. * 精确匹配 title.pali.exact, content.pali.exact, summary
  492. */
  493. protected function buildExactQuery(string $query): array
  494. {
  495. return [
  496. 'multi_match' => [
  497. 'query' => $query,
  498. 'fields' => [
  499. 'title.pali.exact',
  500. 'content.pali.exact',
  501. 'summary.text'
  502. ],
  503. 'type' => 'best_fields',
  504. ]
  505. ];
  506. }
  507. /**
  508. * 构建 semantic 查询
  509. * 使用 OpenAI embedding,同时查询三个向量字段
  510. */
  511. protected function buildSemanticQuery(string $query): array
  512. {
  513. $vector = $this->embedText($query);
  514. // OpenSearch 支持多个 knn 查询,使用 bool should
  515. return [
  516. 'bool' => [
  517. 'should' => [
  518. [
  519. 'knn' => [
  520. 'content.vector' => [
  521. 'vector' => $vector,
  522. 'k' => 20,
  523. ]
  524. ]
  525. ],
  526. [
  527. 'knn' => [
  528. 'summary.vector' => [
  529. 'vector' => $vector,
  530. 'k' => 10,
  531. ]
  532. ]
  533. ],
  534. [
  535. 'knn' => [
  536. 'title.vector' => [
  537. 'vector' => $vector,
  538. 'k' => 5,
  539. ]
  540. ]
  541. ]
  542. ],
  543. 'minimum_should_match' => 1
  544. ]
  545. ];
  546. }
  547. /**
  548. * 构建 fuzzy 查询
  549. */
  550. protected function buildFuzzyQuery(string $query)
  551. {
  552. $fields = [];
  553. foreach ($this->weights['fuzzy'] as $field => $weight) {
  554. $fields[] = $field . "^" . $weight;
  555. }
  556. return [
  557. 'multi_match' => [
  558. 'query' => $query,
  559. 'fields' => $fields,
  560. 'type' => 'best_fields'
  561. ]
  562. ];
  563. }
  564. /**
  565. * 构建 hybrid 查询 (fuzzy + semantic)
  566. */
  567. protected function buildHybridQuery(string $query)
  568. {
  569. $fuzzyFields = [];
  570. foreach ($this->weights['hybrid'] as $field => $weight) {
  571. if (in_array($field, ['fuzzy_ratio', 'semantic_ratio'])) {
  572. continue;
  573. }
  574. $fuzzyFields[] = $field . "^" . $weight;
  575. }
  576. $fuzzyPart = [
  577. 'multi_match' => [
  578. 'query' => $query,
  579. 'fields' => $fuzzyFields,
  580. 'type' => 'best_fields'
  581. ]
  582. ];
  583. $vector = $this->embedText($query);
  584. $fuzzyRatio = $this->weights['hybrid']['fuzzy_ratio'];
  585. $semanticRatio = $this->weights['hybrid']['semantic_ratio'];
  586. // 使用 bool should 组合 fuzzy 和 semantic 查询
  587. return [
  588. 'bool' => [
  589. 'should' => [
  590. // Fuzzy 部分,带权重
  591. [
  592. 'constant_score' => [
  593. 'filter' => $fuzzyPart,
  594. 'boost' => $fuzzyRatio
  595. ]
  596. ],
  597. // Semantic 部分 - content
  598. [
  599. 'knn' => [
  600. 'content.vector' => [
  601. 'vector' => $vector,
  602. 'k' => 20,
  603. 'boost' => $semanticRatio * 1.0 // 主要权重
  604. ]
  605. ]
  606. ],
  607. // Semantic 部分 - summary
  608. [
  609. 'knn' => [
  610. 'summary.vector' => [
  611. 'vector' => $vector,
  612. 'k' => 10,
  613. 'boost' => $semanticRatio * 0.8
  614. ]
  615. ]
  616. ],
  617. // Semantic 部分 - title
  618. [
  619. 'knn' => [
  620. 'title.vector' => [
  621. 'vector' => $vector,
  622. 'k' => 5,
  623. 'boost' => $semanticRatio * 1.2 // title 稍微高一点
  624. ]
  625. ]
  626. ]
  627. ]
  628. ]
  629. ];
  630. }
  631. /**
  632. * 调用 OpenAI Embedding API
  633. * 使用 Redis 缓存,避免重复调用
  634. *
  635. * @param string $text 输入文本
  636. * @return array 向量 embedding
  637. * @throws \Exception
  638. */
  639. protected function embedText(string $text): array
  640. {
  641. if (!$this->openaiApiKey) {
  642. throw new Exception("请在 .env 设置 OPENAI_API_KEY");
  643. }
  644. // 缓存 key,可以用 md5 保证唯一
  645. $cacheKey = "embedding:" . md5($text);
  646. // 先查缓存
  647. return Cache::remember($cacheKey, now()->addDays(7), function () use ($text) {
  648. $response = $this->http->post('embeddings', [
  649. 'headers' => [
  650. 'Authorization' => 'Bearer ' . $this->openaiApiKey,
  651. 'Content-Type' => 'application/json',
  652. ],
  653. 'json' => [
  654. 'model' => 'text-embedding-3-small',
  655. 'input' => $text,
  656. ],
  657. ]);
  658. $json = json_decode((string)$response->getBody(), true);
  659. if (empty($json['data'][0]['embedding'])) {
  660. throw new Exception("OpenAI embedding 返回异常: " . json_encode($json));
  661. }
  662. return $json['data'][0]['embedding'];
  663. });
  664. }
  665. /**
  666. * 清理指定文本的 embedding 缓存
  667. * $service = app(App\Services\OpenSearchService::class);
  668. // 清理某个文本的缓存
  669. $service->clearEmbeddingCache("sabbe dhammā anattā");
  670. // 清理所有 embedding 缓存
  671. $count = $service->clearAllEmbeddingCache();
  672. echo "已清理缓存 {$count} 条";
  673. *
  674. * @param string $text
  675. * @return bool
  676. */
  677. public function clearEmbeddingCache(string $text): bool
  678. {
  679. $cacheKey = "embedding:" . md5($text);
  680. return Cache::forget($cacheKey);
  681. }
  682. /**
  683. * 清理所有 embedding 缓存
  684. * 注意:这会删除 Redis 里所有 "embedding:*" 的缓存
  685. *
  686. * @return int 删除的条数
  687. */
  688. public function clearAllEmbeddingCache(): int
  689. {
  690. $redis = Cache::getRedis();
  691. $pattern = "embedding:*";
  692. $keys = $redis->keys($pattern);
  693. if (!empty($keys)) {
  694. $redis->del($keys);
  695. }
  696. return count($keys);
  697. }
  698. /**
  699. * 自动建议
  700. *
  701. * @param string $query 查询文本
  702. * @param array|string|null $fields 要查询的字段,可选值:
  703. * - null: 查询所有字段 ['title', 'content', 'page_refs']
  704. * - 'title': 只查询 title.suggest
  705. * - 'content': 只查询 content.pali.suggest
  706. * - 'page_refs': 只查询 page_refs.suggest
  707. * - ['title', 'content']: 查询多个字段
  708. * @param string|null $language 语言过滤(可选)
  709. * @param int $limit 每个字段返回的建议数量
  710. * @return array
  711. */
  712. public function suggest(
  713. string $query,
  714. $fields = null,
  715. ?string $language = null,
  716. int $limit = 10
  717. ): array {
  718. // 字段映射配置
  719. $fieldMap = [
  720. 'title' => 'title.suggest',
  721. 'content' => 'content.suggest',
  722. ];
  723. // 处理字段参数
  724. if ($fields === null) {
  725. // 默认查询所有字段
  726. $searchFields = array_keys($fieldMap);
  727. } elseif (is_string($fields)) {
  728. // 单个字段
  729. $searchFields = [$fields];
  730. } else {
  731. // 数组形式
  732. $searchFields = $fields;
  733. }
  734. // 验证字段有效性
  735. $searchFields = array_filter($searchFields, function ($field) use ($fieldMap) {
  736. return isset($fieldMap[$field]);
  737. });
  738. if (empty($searchFields)) {
  739. throw new \InvalidArgumentException('Invalid fields specified for suggestion');
  740. }
  741. // 构建 suggest 查询
  742. $suggests = [];
  743. foreach ($searchFields as $field) {
  744. $suggests[$field . '_suggest'] = [
  745. 'prefix' => $query,
  746. 'completion' => [
  747. 'field' => $fieldMap[$field],
  748. 'size' => $limit,
  749. 'skip_duplicates' => true,
  750. ]
  751. ];
  752. }
  753. $dsl = ['suggest' => $suggests];
  754. // 添加语言过滤
  755. if ($language) {
  756. $dsl['query'] = ['term' => ['language' => $language]];
  757. }
  758. $response = $this->client->search([
  759. 'index' => config('mint.opensearch.index'),
  760. 'body' => $dsl
  761. ]);
  762. // 处理返回结果,包含来源信息
  763. $results = [];
  764. foreach ($searchFields as $field) {
  765. $options = $response['suggest'][$field . '_suggest'][0]['options'] ?? [];
  766. foreach ($options as $opt) {
  767. $results[] = [
  768. 'text' => $opt['text'] ?? '',
  769. 'source' => $field, // 添加来源字段
  770. 'score' => $opt['_score'] ?? 0,
  771. // 可选:添加文档信息
  772. 'doc_id' => $opt['_id'] ?? null,
  773. 'doc_source' => $opt['_source'] ?? null,
  774. ];
  775. }
  776. }
  777. // 按分数排序
  778. usort($results, function ($a, $b) {
  779. return $b['score'] <=> $a['score'];
  780. });
  781. return $results;
  782. }
  783. }