SearchController.php 15 KB

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