2
0

SearchSuggestController.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. <?php
  2. // api-v8/app/Http/Controllers/SearchSuggestController.php
  3. namespace App\Http\Controllers;
  4. use App\Services\OpenSearchService;
  5. use Illuminate\Http\JsonResponse;
  6. use Illuminate\Http\Request;
  7. /**
  8. * 搜索自动建议控制器
  9. *
  10. * 返回示例:
  11. *
  12. * 请求:GET /api/v3/search-suggest?q=dhamma&fields=title,content&limit=10
  13. *
  14. * 返回:
  15. * {
  16. * "success": true,
  17. * "data": {
  18. * "query": "dhamma",
  19. * "suggestions": [
  20. {
  21. "text": "dhammacakkapavattanasutta",
  22. "source": "content",
  23. "score": 1,
  24. "resource_type": "term",
  25. "language": "zh",
  26. "doc_id": "term_69258244-bccd-40ed-bfaa-ddef4ae5ae4c",
  27. "category": [],
  28. "granularity": null
  29. },
  30. {
  31. "text": "dhammacakkappavattanasutta",
  32. "source": "content",
  33. "score": 1,
  34. "resource_type": "term",
  35. "language": "zh-hans",
  36. "doc_id": "term_bcb14399-ea80-4a8a-aeab-a4c927e45fdd",
  37. "category": [],
  38. "granularity": null
  39. }
  40. * ],
  41. * "total": 2
  42. * }
  43. * }
  44. */
  45. class SearchSuggestController extends Controller
  46. {
  47. protected $searchService;
  48. /**
  49. * 构造函数,注入 OpenSearchService
  50. */
  51. public function __construct(OpenSearchService $searchService)
  52. {
  53. $this->searchService = $searchService;
  54. }
  55. /**
  56. * # 1. 查询所有字段(默认)
  57. GET /api/v2/suggest?q=dhamma&limit=10
  58. # 2. 只查询标题
  59. GET /api/v2/suggest?q=dhamma&fields=title&limit=10
  60. # 3. 查询标题和内容
  61. GET /api/v2/suggest?q=dhamma&fields=title,content&limit=10
  62. # 4. 查询页面引用,带语言过滤
  63. GET /api/v2/suggest?q=M.1&fields=page_refs&language=pali&limit=5
  64. # 5. 数组形式传递多个字段
  65. GET /api/v2/suggest?q=dhamma&fields[]=title&fields[]=content&limit=10
  66. */
  67. /**
  68. * 自动建议接口
  69. *
  70. * 基于 OpenSearch completion suggester,支持从不同字段获取建议。
  71. *
  72. * @param Request $request
  73. * - q (string): 输入的部分文本(必填)
  74. * - fields (string|array): 要查询的字段,可选值:
  75. * - 不传:查询所有字段 (title, content, page_refs)
  76. * - 单个字段:'title' | 'content' | 'page_refs'
  77. * - 多个字段:'title,content' 或 ['title', 'content']
  78. * - language (string): 语言过滤,可选(如:pali, zh, en)
  79. * - limit (int): 每个字段返回的建议数量,默认 10,最大 50
  80. * @return JsonResponse
  81. */
  82. public function index(Request $request)
  83. {
  84. // 验证必填参数
  85. $query = $request->input('q', '');
  86. if (empty($query)) {
  87. return response()->json([
  88. 'success' => false,
  89. 'error' => '缺少参数 q(查询文本)',
  90. ], 400);
  91. }
  92. // 解析 fields 参数
  93. $fields = $this->parseFields($request->input('fields'));
  94. // 获取其他参数
  95. $language = $request->input('language', null);
  96. $limit = min(50, max(1, (int) $request->input('limit', 10)));
  97. try {
  98. // 调用搜索服务
  99. $rawSuggestions = $this->searchService->suggest(
  100. $query,
  101. $fields,
  102. $language,
  103. $limit
  104. );
  105. // 格式化返回结果
  106. $suggestions = $this->formatSuggestions($rawSuggestions);
  107. return response()->json([
  108. 'success' => true,
  109. 'data' => [
  110. 'query' => $query,
  111. 'suggestions' => $suggestions,
  112. 'total' => count($suggestions),
  113. ],
  114. ]);
  115. } catch (\InvalidArgumentException $e) {
  116. return response()->json([
  117. 'success' => false,
  118. 'error' => '无效的字段参数:'.$e->getMessage(),
  119. 'hint' => '有效的字段值:title, content, page_refs',
  120. ], 400);
  121. } catch (\Exception $e) {
  122. return response()->json([
  123. 'success' => false,
  124. 'error' => '搜索建议失败:'.$e->getMessage(),
  125. ], 500);
  126. }
  127. }
  128. /**
  129. * 解析 fields 参数
  130. *
  131. * @param mixed $fields
  132. * @return string|array|null
  133. */
  134. protected function parseFields($fields)
  135. {
  136. if ($fields === null) {
  137. return null; // 查询所有字段
  138. }
  139. if (is_string($fields)) {
  140. // 如果是逗号分隔的字符串,转换为数组
  141. if (strpos($fields, ',') !== false) {
  142. $fieldsArray = array_map('trim', explode(',', $fields));
  143. return $fieldsArray;
  144. }
  145. // 单个字段
  146. return $fields;
  147. }
  148. if (is_array($fields)) {
  149. return $fields;
  150. }
  151. return null;
  152. }
  153. /**
  154. * 格式化建议结果
  155. */
  156. protected function formatSuggestions(array $rawSuggestions): array
  157. {
  158. return collect($rawSuggestions)->map(function ($item) {
  159. $docSource = $item['doc_source'] ?? [];
  160. return [
  161. 'text' => $item['text'] ?? '',
  162. 'source' => $item['source'] ?? null,
  163. 'score' => round($item['score'] ?? 0, 2),
  164. 'resource_type' => $docSource['resource_type'] ?? null,
  165. 'language' => $docSource['language'] ?? null,
  166. 'doc_id' => $item['doc_id'] ?? null,
  167. // 可选:添加更多元数据
  168. 'category' => $docSource['category'] ?? null,
  169. 'granularity' => $docSource['granularity'] ?? null,
  170. ];
  171. })->all();
  172. }
  173. }