2
0

SearchSuggestController.php 5.5 KB

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