SearchController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use App\Models\BookTitle;
  5. use App\Models\FtsText;
  6. use App\Models\Tag;
  7. use App\Models\TagMap;
  8. use App\Models\PaliText;
  9. use Illuminate\Support\Facades\Http;
  10. use Illuminate\Support\Facades\DB;
  11. use App\Http\Resources\SearchResource;
  12. use App\Http\Resources\SearchTitleResource;
  13. use App\Http\Resources\SearchBookResource;
  14. use Illuminate\Support\Facades\Log;
  15. use App\Tools\Tools;
  16. use App\Models\WbwTemplate;
  17. use App\Models\PageNumber;
  18. use App\Tools\PaliSearch;
  19. use Illuminate\Support\Facades\App;
  20. class SearchController extends Controller
  21. {
  22. /**
  23. * Display a listing of the resource.
  24. *
  25. * @return \Illuminate\Http\Response
  26. */
  27. public function index(Request $request){
  28. switch ($request->get('view','pali')) {
  29. case 'pali':
  30. $pageHead = ['M','P','T','V','O'];
  31. $key = $request->get('key');
  32. if(substr($key,0,4) === 'para' || in_array(substr($key,0,1),$pageHead)){
  33. return $this->page($request);
  34. }else{
  35. return $this->pali_rpc($request);
  36. }
  37. break;
  38. case 'page':
  39. return $this->page($request);
  40. break;
  41. case 'title':
  42. $key = strtolower($request->get('key'));
  43. $table = PaliText::where('level','<',8)
  44. ->where(function ($query) use($key){
  45. $query->where('title_en','like',"%{$key}%")
  46. ->orWhere('title','like',"%{$key}%");
  47. });
  48. Log::info($table->toSql());
  49. if($request->has('tags')){
  50. //查询搜索范围
  51. $tagItems = explode(';',$request->get('tags'));
  52. $bookId = [];
  53. foreach ($tagItems as $tagItem) {
  54. # code...
  55. $bookId = array_merge($bookId,$this->getBookIdByTags(explode(',',$tagItem)));
  56. }
  57. $table = $table->whereIn('pcd_book_id',$bookId);
  58. }
  59. $count = $table->count();
  60. $table = $table->orderBy($request->get('orderby','book'),$request->get('dir','asc'));
  61. $table = $table->skip($request->get("offset",0))
  62. ->take($request->get('limit',10));
  63. $result = $table->get();
  64. return $this->ok(["rows"=>SearchTitleResource::collection($result),"count"=>$count]);
  65. break;
  66. default:
  67. # code...
  68. break;
  69. }
  70. }
  71. public function pali(Request $request)
  72. {
  73. //
  74. $bookId = [];
  75. if($request->has('book')){
  76. $bookId = [(int)$request->get('book')];
  77. }else if($request->has('tags')){
  78. //查询搜索范围
  79. //查询搜索范围
  80. $tagItems = explode(';',$request->get('tags'));
  81. foreach ($tagItems as $tagItem) {
  82. $bookId = array_merge($bookId,$this->getBookIdByTags(explode(',',$tagItem)));
  83. }
  84. }
  85. $searchChapters = [];
  86. $searchBooks = [];
  87. $searchBookId = [];
  88. $queryBookId = '';
  89. if(count($bookId) > 0){
  90. $queryBookId = ' AND pcd_book_id in ('.implode(',',$bookId).') ';
  91. }
  92. $key = explode(';',$request->get('key')) ;
  93. $param = [];
  94. $countParam = [];
  95. switch ($request->get('match','case')) {
  96. case 'complete':
  97. case 'case':
  98. # code...
  99. $querySelect_rank_base = " ts_rank('{0.1, 1, 0.3, 0.2}',
  100. full_text_search_weighted,
  101. websearch_to_tsquery('pali', ?)) ";
  102. $querySelect_rank_head = implode('+', array_fill(0, count($key), $querySelect_rank_base));
  103. $param = array_merge($param,$key);
  104. $querySelect_rank = " {$querySelect_rank_head} AS rank, ";
  105. $querySelect_highlight = " ts_headline('pali', content,
  106. websearch_to_tsquery('pali', ?),
  107. 'StartSel = ~~, StopSel = ~~,MaxWords=3500, MinWords=3500,HighlightAll=TRUE')
  108. AS highlight,";
  109. array_push($param,implode(' ',$key));
  110. break;
  111. case 'similar':
  112. # 形似,去掉变音符号
  113. $key = Tools::getWordEn($key[0]);
  114. $querySelect_rank = "
  115. ts_rank('{0.1, 1, 0.3, 0.2}',
  116. full_text_search_weighted_unaccent,
  117. websearch_to_tsquery('pali_unaccent', ?))
  118. AS rank, ";
  119. $param[] = $key;
  120. $querySelect_highlight = " ts_headline('pali_unaccent', content,
  121. websearch_to_tsquery('pali_unaccent', ?),
  122. 'StartSel = ~~, StopSel = ~~,MaxWords=3500, MinWords=3500,HighlightAll=TRUE')
  123. AS highlight,";
  124. $param[] = $key;
  125. break;
  126. }
  127. $_queryWhere = $this->getQueryWhere($request->get('key'),$request->get('match','case'));
  128. $queryWhere = $_queryWhere['query'];
  129. $param = array_merge($param,$_queryWhere['param']);
  130. $querySelect_2 = " book,paragraph,content ";
  131. $queryCount = "SELECT count(*) as co FROM fts_texts WHERE {$queryWhere} {$queryBookId};";
  132. $resultCount = DB::select($queryCount, $_queryWhere['param']);
  133. $limit = $request->get('limit',10);
  134. $offset = $request->get('offset',0);
  135. switch ( $request->get('orderby',"rank")) {
  136. case 'rank':
  137. $orderby = " ORDER BY rank DESC ";
  138. break;
  139. case 'paragraph':
  140. $orderby = " ORDER BY book,paragraph ";
  141. break;
  142. default:
  143. $orderby = "";
  144. break;
  145. };
  146. $query = "SELECT
  147. {$querySelect_rank}
  148. {$querySelect_highlight}
  149. {$querySelect_2}
  150. FROM fts_texts
  151. WHERE
  152. {$queryWhere}
  153. {$queryBookId}
  154. {$orderby}
  155. LIMIT ? OFFSET ? ;";
  156. $param[] = $limit;
  157. $param[] = $offset;
  158. $result = DB::select($query, $param);
  159. return $this->ok(["rows"=>SearchResource::collection($result),"count"=>$resultCount[0]->co]);
  160. }
  161. public function pali_rpc(Request $request)
  162. {
  163. //
  164. $bookId = [];
  165. if($request->has('book')){
  166. $bookId = [(int)$request->get('book')];
  167. }else if($request->has('tags')){
  168. //查询搜索范围
  169. //查询搜索范围
  170. $tagItems = explode(';',$request->get('tags'));
  171. foreach ($tagItems as $tagItem) {
  172. $bookId = array_merge($bookId,$this->getBookIdByTags(explode(',',$tagItem)));
  173. }
  174. }
  175. $key = explode(';',$request->get('key')) ;
  176. $limit = $request->get('limit',10);
  177. $offset = $request->get('offset',0);
  178. $matchMode = $request->get('match','case');
  179. $result = PaliSearch::search($key,$bookId,$matchMode,$offset,$limit);
  180. Log::debug('search tulip total='.$result['total'],[
  181. 'key'=>$request->get('key'),
  182. 'bookId'=>$bookId,
  183. 'matchMode'=>$matchMode,
  184. 'offset'=>$offset,
  185. 'limit'=>$limit,
  186. ]);
  187. return $this->ok(["rows"=>SearchResource::collection(collect($result['rows'])),"count"=>$result['total']]);
  188. }
  189. public function page(Request $request)
  190. {
  191. //
  192. $searchChapters = [];
  193. $searchBooks = [];
  194. $searchBookId = [];
  195. $queryBookId = '';
  196. $bookId = [];
  197. if($request->has('book')){
  198. $bookId[] = $request->get('book');
  199. }else if($request->has('tags')){
  200. //查询搜索范围
  201. //查询搜索范围
  202. $tagItems = explode(';',$request->get('tags'));
  203. foreach ($tagItems as $tagItem) {
  204. # code...
  205. $bookId = array_merge($bookId,$this->getBookIdByTags(explode(',',$tagItem)));
  206. }
  207. }
  208. $key = $request->get('key');
  209. $searchKey = '';
  210. $page = explode('.',$key);
  211. if(count($page)===2){
  212. $table = PageNumber::where('type',$request->get('type'))
  213. ->where('volume',(int)$page[0])
  214. ->where('page',(int)$page[1]);
  215. }else{
  216. if(is_numeric($key)){
  217. $table = PageNumber::where('type',$request->get('type'))->where('page',$key);
  218. }else{
  219. $table = PageNumber::where('type',$request->get('type'))->where('page',(int)$key);
  220. }
  221. }
  222. if(count($bookId)>0){
  223. $table = $table->whereIn('pcd_book_id',$bookId);
  224. }
  225. $count = $table->count();
  226. $table = $table->select(['book','paragraph']);
  227. $table->skip($request->get("offset",0))->take($request->get('limit',10));
  228. $result = $table->get();
  229. return $this->ok(["rows"=>SearchResource::collection($result),"count"=>$count]);
  230. }
  231. public function book_list(Request $request){
  232. $searchChapters = [];
  233. $searchBooks = [];
  234. $queryBookId = '';
  235. $bookId = [];
  236. if($request->has('tags')){
  237. //查询搜索范围
  238. $tagItems = explode(';',$request->get('tags'));
  239. foreach ($tagItems as $tagItem) {
  240. # code...
  241. $bookId = array_merge($bookId,$this->getBookIdByTags(explode(',',$tagItem)));
  242. }
  243. $queryBookId = ' AND pcd_book_id in ('.implode(',',$bookId).') ';
  244. }
  245. $key = $request->get('key');
  246. switch ($request->get('view','pali')) {
  247. case 'pali':
  248. # code...
  249. $pageHead = ['M','P','T','V','O'];
  250. if(substr($key,0,4) === 'para' || in_array(substr($key,0,1),$pageHead)){
  251. $queryWhere = "type='.ctl.' AND word = ?";
  252. $query = "SELECT pcd_book_id, count(*) as co FROM wbw_templates WHERE {$queryWhere} {$queryBookId} GROUP BY pcd_book_id ORDER BY co DESC;";
  253. $result = DB::select($query, [$key]);
  254. }else{
  255. if (App::environment(['local', 'staging'])) {
  256. $rpc_result = PaliSearch::book_list(explode(';',$key) ,$bookId,
  257. $request->get('match','case'));
  258. $result = collect($rpc_result['rows']);
  259. }else{
  260. $queryWhere = $this->getQueryWhere($key,$request->get('match','case'));
  261. $query = "SELECT pcd_book_id, count(*) as co FROM fts_texts WHERE {$queryWhere['query']} {$queryBookId} GROUP BY pcd_book_id ORDER BY co DESC;";
  262. $result = DB::select($query, $queryWhere['param']);
  263. }
  264. }
  265. break;
  266. case 'page':
  267. $type = $request->get('type','P');
  268. $word = "{$type}%0{$key}";
  269. $queryWhere = "type='.ctl.' AND word like ?";
  270. $query = "SELECT pcd_book_id, count(*) as co FROM wbw_templates WHERE {$queryWhere} {$queryBookId} GROUP BY pcd_book_id ORDER BY co DESC;";
  271. $result = DB::select($query, [$word]);
  272. break;
  273. case 'title':
  274. $keyLike = '%'.$key.'%';
  275. $queryWhere = "\"level\" < 8 and (\"title_en\"::text like ? or \"title\"::text like ?)";
  276. $query = "SELECT pcd_book_id, count(*) as co FROM pali_texts WHERE {$queryWhere} {$queryBookId} GROUP BY pcd_book_id ORDER BY co DESC;";
  277. $result = DB::select($query, [$keyLike,$keyLike]);
  278. break;
  279. default:
  280. # code...
  281. return $this->error('unknown view');
  282. break;
  283. }
  284. if($result){
  285. return $this->ok(["rows"=>SearchBookResource::collection($result),"count"=>count($result)]);
  286. }else{
  287. return $this->ok(["rows"=>[],"count"=>0]);
  288. }
  289. }
  290. private function getQueryWhere($key,$match){
  291. $key = explode(';',$key) ;
  292. $param = [];
  293. $queryWhere = '';
  294. switch ($match) {
  295. case 'complete':
  296. case 'case':
  297. # code...
  298. $queryWhereBase = " full_text_search_weighted @@ websearch_to_tsquery('pali', ?) ";
  299. $queryWhereBody = implode(' or ', array_fill(0, count($key), $queryWhereBase));
  300. $queryWhere = " ({$queryWhereBody}) ";
  301. $param = array_merge($param,$key);
  302. break;
  303. case 'similar':
  304. # 形似,去掉变音符号
  305. $queryWhere = " full_text_search_weighted_unaccent @@ websearch_to_tsquery('pali_unaccent', ?) ";
  306. $key = Tools::getWordEn($key[0]);
  307. $param = [$key];
  308. break;
  309. };
  310. return (['query'=>$queryWhere,'param'=>$param]);
  311. }
  312. public function getBookIdByTags($tags){
  313. $searchBookId = [];
  314. if(empty($tags)){
  315. return $searchBookId;
  316. }
  317. //查询搜索范围
  318. $tagIds = Tag::whereIn('name',$tags)->select('id')->get();
  319. $paliTextIds = TagMap::where('table_name','pali_texts')->whereIn('tag_id',$tagIds)->select('anchor_id')->get();
  320. $paliPara=[];
  321. foreach ($paliTextIds as $key => $value) {
  322. # code...
  323. if(isset($paliPara[$value->anchor_id])){
  324. $paliPara[$value->anchor_id]++;
  325. }else{
  326. $paliPara[$value->anchor_id]=1;
  327. }
  328. }
  329. $paliId=[];
  330. foreach ($paliPara as $key => $value) {
  331. # code...
  332. if($value===count($tags)){
  333. $paliId[] = $key;
  334. }
  335. }
  336. $para = PaliText::where('level',1)->whereIn('uid',$paliId)->get();
  337. if(count($para)>0){
  338. foreach ($para as $key => $value) {
  339. # code...
  340. $book_id = BookTitle::where('book',$value['book'])
  341. ->where('paragraph',$value['paragraph'])
  342. ->value('sn');
  343. if(!empty($book_id)){
  344. $searchBookId[] = $book_id;
  345. }
  346. }
  347. }
  348. return $searchBookId;
  349. }
  350. /**
  351. * Store a newly created resource in storage.
  352. *
  353. * @param \Illuminate\Http\Request $request
  354. * @return \Illuminate\Http\Response
  355. */
  356. public function store(Request $request)
  357. {
  358. //
  359. }
  360. /**
  361. * Display the specified resource.
  362. *
  363. * @param int $id
  364. * @return \Illuminate\Http\Response
  365. */
  366. public function show($id)
  367. {
  368. //
  369. }
  370. /**
  371. * Update the specified resource in storage.
  372. *
  373. * @param \Illuminate\Http\Request $request
  374. * @param int $id
  375. * @return \Illuminate\Http\Response
  376. */
  377. public function update(Request $request, $id)
  378. {
  379. //
  380. }
  381. /**
  382. * Remove the specified resource from storage.
  383. *
  384. * @param int $id
  385. * @return \Illuminate\Http\Response
  386. */
  387. public function destroy($id)
  388. {
  389. //
  390. }
  391. }