SearchSuggestController.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. <?php
  2. // api-v8/app/Http/Controllers/SearchSuggestController.php
  3. namespace App\Http\Controllers\V3;
  4. use App\Http\Controllers\Controller;
  5. use App\Services\OpenSearchService;
  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. * 按前缀给出补全候选,供搜索框实时提示。每个字段各自返回一组建议。
  71. * q 为空时返回 400。
  72. *
  73. * @unauthenticated
  74. *
  75. * @queryParam q string required 已输入的查询文本
  76. * @queryParam fields string 在哪些字段上补全,逗号分隔;不传则全查。
  77. * Enum: title,content,page_refs
  78. * @queryParam language string 语言过滤。Example: pali
  79. * @queryParam limit integer 每个字段返回的建议数,上限 50。Default: 10
  80. */
  81. public function index(Request $request)
  82. {
  83. // 验证必填参数
  84. $query = $request->input('q', '');
  85. if (empty($query)) {
  86. return response()->json([
  87. 'success' => false,
  88. 'error' => '缺少参数 q(查询文本)',
  89. ], 400);
  90. }
  91. // 解析 fields 参数
  92. $fields = $this->parseFields($request->input('fields'));
  93. // 获取其他参数
  94. $language = $request->input('language', null);
  95. $limit = min(50, max(1, (int) $request->input('limit', 10)));
  96. try {
  97. // 调用搜索服务
  98. $rawSuggestions = $this->searchService->suggest(
  99. $query,
  100. $fields,
  101. $language,
  102. $limit
  103. );
  104. // 格式化返回结果
  105. $suggestions = $this->formatSuggestions($rawSuggestions);
  106. return response()->json([
  107. 'success' => true,
  108. 'data' => [
  109. 'query' => $query,
  110. 'suggestions' => $suggestions,
  111. 'total' => count($suggestions),
  112. ],
  113. ]);
  114. } catch (\InvalidArgumentException $e) {
  115. return response()->json([
  116. 'success' => false,
  117. 'error' => '无效的字段参数:'.$e->getMessage(),
  118. 'hint' => '有效的字段值:title, content, page_refs',
  119. ], 400);
  120. } catch (\Exception $e) {
  121. return response()->json([
  122. 'success' => false,
  123. 'error' => '搜索建议失败:'.$e->getMessage(),
  124. ], 500);
  125. }
  126. }
  127. /**
  128. * 解析 fields 参数
  129. *
  130. * @param mixed $fields
  131. * @return string|array|null
  132. */
  133. protected function parseFields($fields)
  134. {
  135. if ($fields === null) {
  136. return null; // 查询所有字段
  137. }
  138. if (is_string($fields)) {
  139. // 如果是逗号分隔的字符串,转换为数组
  140. if (strpos($fields, ',') !== false) {
  141. $fieldsArray = array_map('trim', explode(',', $fields));
  142. return $fieldsArray;
  143. }
  144. // 单个字段
  145. return $fields;
  146. }
  147. if (is_array($fields)) {
  148. return $fields;
  149. }
  150. return null;
  151. }
  152. /**
  153. * 格式化建议结果
  154. */
  155. protected function formatSuggestions(array $rawSuggestions): array
  156. {
  157. return collect($rawSuggestions)->map(function ($item) {
  158. $docSource = $item['doc_source'] ?? [];
  159. return [
  160. 'text' => $item['text'] ?? '',
  161. 'source' => $item['source'] ?? null,
  162. 'score' => round($item['score'] ?? 0, 2),
  163. 'resource_type' => $docSource['resource_type'] ?? null,
  164. 'language' => $docSource['language'] ?? null,
  165. 'doc_id' => $item['doc_id'] ?? null,
  166. // 可选:添加更多元数据
  167. 'category' => $docSource['category'] ?? null,
  168. 'granularity' => $docSource['granularity'] ?? null,
  169. ];
  170. })->all();
  171. }
  172. }