OpenSearchService.php 27 KB

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