OpenSearchService.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. // ---------- 最终 DSL ----------
  398. $dsl = [
  399. 'from' => $from,
  400. 'size' => $pageSize,
  401. '_source' => [
  402. 'excludes' => $this->sourceExcludes
  403. ],
  404. 'query' => !empty($filters)
  405. ? ['bool' => ['must' => [$query], 'filter' => $filters]]
  406. : $query,
  407. 'aggs' => [
  408. 'resource_type' => ['terms' => ['field' => 'resource_type']],
  409. 'language' => ['terms' => ['field' => 'language']],
  410. 'category' => ['terms' => ['field' => 'category']],
  411. 'granularity' => ['terms' => ['field' => 'granularity']],
  412. ],
  413. 'highlight' => [
  414. 'fields' => [
  415. 'title.pali.text' => new \stdClass(),
  416. 'title.zh' => new \stdClass(),
  417. 'summary.text' => new \stdClass(),
  418. 'content.pali.text' => new \stdClass(),
  419. 'content.zh' => new \stdClass(),
  420. ],
  421. "fragmenter" => "sentence",
  422. "fragment_size" => 200,
  423. "number_of_fragments" => 1,
  424. 'pre_tags' => ['_'],
  425. 'post_tags' => ['_'],
  426. ],
  427. ];
  428. Log::debug('search', ['dsl' => json_encode($dsl, JSON_UNESCAPED_UNICODE)]);
  429. // ---------- 执行查询 ----------
  430. $response = $this->client->search([
  431. 'index' => config('mint.opensearch.index'),
  432. 'body' => $dsl
  433. ]);
  434. return $response;
  435. }
  436. /**
  437. * 构建 exact 查询
  438. * 精确匹配 title.pali.exact, content.pali.exact, summary
  439. */
  440. protected function buildExactQuery(string $query): array
  441. {
  442. return [
  443. 'multi_match' => [
  444. 'query' => $query,
  445. 'fields' => [
  446. 'title.pali.exact',
  447. 'content.pali.exact',
  448. 'summary.text'
  449. ],
  450. 'type' => 'best_fields',
  451. ]
  452. ];
  453. }
  454. /**
  455. * 构建 semantic 查询
  456. * 使用 OpenAI embedding,同时查询三个向量字段
  457. */
  458. protected function buildSemanticQuery(string $query): array
  459. {
  460. $vector = $this->embedText($query);
  461. // OpenSearch 支持多个 knn 查询,使用 bool should
  462. return [
  463. 'bool' => [
  464. 'should' => [
  465. [
  466. 'knn' => [
  467. 'content.vector' => [
  468. 'vector' => $vector,
  469. 'k' => 20,
  470. ]
  471. ]
  472. ],
  473. [
  474. 'knn' => [
  475. 'summary.vector' => [
  476. 'vector' => $vector,
  477. 'k' => 10,
  478. ]
  479. ]
  480. ],
  481. [
  482. 'knn' => [
  483. 'title.vector' => [
  484. 'vector' => $vector,
  485. 'k' => 5,
  486. ]
  487. ]
  488. ]
  489. ],
  490. 'minimum_should_match' => 1
  491. ]
  492. ];
  493. }
  494. /**
  495. * 构建 fuzzy 查询
  496. */
  497. protected function buildFuzzyQuery(string $query)
  498. {
  499. $fields = [];
  500. foreach ($this->weights['fuzzy'] as $field => $weight) {
  501. $fields[] = $field . "^" . $weight;
  502. }
  503. return [
  504. 'multi_match' => [
  505. 'query' => $query,
  506. 'fields' => $fields,
  507. 'type' => 'best_fields'
  508. ]
  509. ];
  510. }
  511. /**
  512. * 构建 hybrid 查询 (fuzzy + semantic)
  513. */
  514. protected function buildHybridQuery(string $query)
  515. {
  516. $fuzzyFields = [];
  517. foreach ($this->weights['hybrid'] as $field => $weight) {
  518. if (in_array($field, ['fuzzy_ratio', 'semantic_ratio'])) {
  519. continue;
  520. }
  521. $fuzzyFields[] = $field . "^" . $weight;
  522. }
  523. $fuzzyPart = [
  524. 'multi_match' => [
  525. 'query' => $query,
  526. 'fields' => $fuzzyFields,
  527. 'type' => 'best_fields'
  528. ]
  529. ];
  530. $vector = $this->embedText($query);
  531. $fuzzyRatio = $this->weights['hybrid']['fuzzy_ratio'];
  532. $semanticRatio = $this->weights['hybrid']['semantic_ratio'];
  533. // 使用 bool should 组合 fuzzy 和 semantic 查询
  534. return [
  535. 'bool' => [
  536. 'should' => [
  537. // Fuzzy 部分,带权重
  538. [
  539. 'constant_score' => [
  540. 'filter' => $fuzzyPart,
  541. 'boost' => $fuzzyRatio
  542. ]
  543. ],
  544. // Semantic 部分 - content
  545. [
  546. 'knn' => [
  547. 'content.vector' => [
  548. 'vector' => $vector,
  549. 'k' => 20,
  550. 'boost' => $semanticRatio * 1.0 // 主要权重
  551. ]
  552. ]
  553. ],
  554. // Semantic 部分 - summary
  555. [
  556. 'knn' => [
  557. 'summary.vector' => [
  558. 'vector' => $vector,
  559. 'k' => 10,
  560. 'boost' => $semanticRatio * 0.8
  561. ]
  562. ]
  563. ],
  564. // Semantic 部分 - title
  565. [
  566. 'knn' => [
  567. 'title.vector' => [
  568. 'vector' => $vector,
  569. 'k' => 5,
  570. 'boost' => $semanticRatio * 1.2 // title 稍微高一点
  571. ]
  572. ]
  573. ]
  574. ]
  575. ]
  576. ];
  577. }
  578. /**
  579. * 调用 OpenAI Embedding API
  580. * 使用 Redis 缓存,避免重复调用
  581. *
  582. * @param string $text 输入文本
  583. * @return array 向量 embedding
  584. * @throws \Exception
  585. */
  586. protected function embedText(string $text): array
  587. {
  588. if (!$this->openaiApiKey) {
  589. throw new Exception("请在 .env 设置 OPENAI_API_KEY");
  590. }
  591. // 缓存 key,可以用 md5 保证唯一
  592. $cacheKey = "embedding:" . md5($text);
  593. // 先查缓存
  594. return Cache::remember($cacheKey, now()->addDays(7), function () use ($text) {
  595. $response = $this->http->post('embeddings', [
  596. 'headers' => [
  597. 'Authorization' => 'Bearer ' . $this->openaiApiKey,
  598. 'Content-Type' => 'application/json',
  599. ],
  600. 'json' => [
  601. 'model' => 'text-embedding-3-small',
  602. 'input' => $text,
  603. ],
  604. ]);
  605. $json = json_decode((string)$response->getBody(), true);
  606. if (empty($json['data'][0]['embedding'])) {
  607. throw new Exception("OpenAI embedding 返回异常: " . json_encode($json));
  608. }
  609. return $json['data'][0]['embedding'];
  610. });
  611. }
  612. /**
  613. * 清理指定文本的 embedding 缓存
  614. * $service = app(App\Services\OpenSearchService::class);
  615. // 清理某个文本的缓存
  616. $service->clearEmbeddingCache("sabbe dhammā anattā");
  617. // 清理所有 embedding 缓存
  618. $count = $service->clearAllEmbeddingCache();
  619. echo "已清理缓存 {$count} 条";
  620. *
  621. * @param string $text
  622. * @return bool
  623. */
  624. public function clearEmbeddingCache(string $text): bool
  625. {
  626. $cacheKey = "embedding:" . md5($text);
  627. return Cache::forget($cacheKey);
  628. }
  629. /**
  630. * 清理所有 embedding 缓存
  631. * 注意:这会删除 Redis 里所有 "embedding:*" 的缓存
  632. *
  633. * @return int 删除的条数
  634. */
  635. public function clearAllEmbeddingCache(): int
  636. {
  637. $redis = Cache::getRedis();
  638. $pattern = "embedding:*";
  639. $keys = $redis->keys($pattern);
  640. if (!empty($keys)) {
  641. $redis->del($keys);
  642. }
  643. return count($keys);
  644. }
  645. /**
  646. * 自动建议
  647. *
  648. * @param string $query 查询文本
  649. * @param array|string|null $fields 要查询的字段,可选值:
  650. * - null: 查询所有字段 ['title', 'content', 'page_refs']
  651. * - 'title': 只查询 title.suggest
  652. * - 'content': 只查询 content.pali.suggest
  653. * - 'page_refs': 只查询 page_refs.suggest
  654. * - ['title', 'content']: 查询多个字段
  655. * @param string|null $language 语言过滤(可选)
  656. * @param int $limit 每个字段返回的建议数量
  657. * @return array
  658. */
  659. public function suggest(
  660. string $query,
  661. $fields = null,
  662. ?string $language = null,
  663. int $limit = 10
  664. ): array {
  665. // 字段映射配置
  666. $fieldMap = [
  667. 'title' => 'title.suggest',
  668. 'content' => 'content.suggest',
  669. ];
  670. // 处理字段参数
  671. if ($fields === null) {
  672. // 默认查询所有字段
  673. $searchFields = array_keys($fieldMap);
  674. } elseif (is_string($fields)) {
  675. // 单个字段
  676. $searchFields = [$fields];
  677. } else {
  678. // 数组形式
  679. $searchFields = $fields;
  680. }
  681. // 验证字段有效性
  682. $searchFields = array_filter($searchFields, function ($field) use ($fieldMap) {
  683. return isset($fieldMap[$field]);
  684. });
  685. if (empty($searchFields)) {
  686. throw new \InvalidArgumentException('Invalid fields specified for suggestion');
  687. }
  688. // 构建 suggest 查询
  689. $suggests = [];
  690. foreach ($searchFields as $field) {
  691. $suggests[$field . '_suggest'] = [
  692. 'prefix' => $query,
  693. 'completion' => [
  694. 'field' => $fieldMap[$field],
  695. 'size' => $limit,
  696. 'skip_duplicates' => true,
  697. ]
  698. ];
  699. }
  700. $dsl = ['suggest' => $suggests];
  701. // 添加语言过滤
  702. if ($language) {
  703. $dsl['query'] = ['term' => ['language' => $language]];
  704. }
  705. $response = $this->client->search([
  706. 'index' => config('mint.opensearch.index'),
  707. 'body' => $dsl
  708. ]);
  709. // 处理返回结果,包含来源信息
  710. $results = [];
  711. foreach ($searchFields as $field) {
  712. $options = $response['suggest'][$field . '_suggest'][0]['options'] ?? [];
  713. foreach ($options as $opt) {
  714. $results[] = [
  715. 'text' => $opt['text'] ?? '',
  716. 'source' => $field, // 添加来源字段
  717. 'score' => $opt['_score'] ?? 0,
  718. // 可选:添加文档信息
  719. 'doc_id' => $opt['_id'] ?? null,
  720. 'doc_source' => $opt['_source'] ?? null,
  721. ];
  722. }
  723. }
  724. // 按分数排序
  725. usort($results, function ($a, $b) {
  726. return $b['score'] <=> $a['score'];
  727. });
  728. return $results;
  729. }
  730. }