DbSearcher.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. //const _ = require('lodash');
  2. const utils = require('./utils');
  3. const maxUtf8Char = String.fromCodePoint(0xFFFFF);
  4. const ruAlphabet = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
  5. const enAlphabet = 'abcdefghijklmnopqrstuvwxyz';
  6. const enruArr = (ruAlphabet + enAlphabet).split('');
  7. class DbSearcher {
  8. constructor(config, db) {
  9. this.config = config;
  10. this.db = db;
  11. this.searchFlag = 0;
  12. this.timer = null;
  13. this.closed = false;
  14. this.periodicCleanCache();//no await
  15. }
  16. getWhere(a) {
  17. const db = this.db;
  18. a = a.toLowerCase();
  19. let where;
  20. //особая обработка префиксов
  21. if (a[0] == '=') {
  22. a = a.substring(1);
  23. where = `@@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a)})`;
  24. } else if (a[0] == '*') {
  25. a = a.substring(1);
  26. where = `@@indexIter('value', (v) => (v.indexOf(${db.esc(a)}) >= 0) )`;
  27. } else if (a[0] == '#') {
  28. a = a.substring(1);
  29. where = `@@indexIter('value', (v) => {
  30. const enru = new Set(${db.esc(enruArr)});
  31. return !v || !enru.has(v[0].toLowerCase());
  32. });`;
  33. } else {
  34. where = `@@dirtyIndexLR('value', ${db.esc(a)}, ${db.esc(a + maxUtf8Char)})`;
  35. }
  36. return where;
  37. }
  38. async selectAuthorIds(query) {
  39. const db = this.db;
  40. let authorIds = new Set();
  41. //сначала выберем все id авторов по фильтру
  42. //порядок id соответсвует ASC-сортировке по author
  43. if (query.author && query.author !== '*') {
  44. const where = this.getWhere(query.author);
  45. const authorRows = await db.select({
  46. table: 'author',
  47. dirtyIdsOnly: true,
  48. where
  49. });
  50. for (const row of authorRows)
  51. authorIds.add(row.id);
  52. } else {//все авторы
  53. if (!db.searchCache.authorIdsAll) {
  54. const authorRows = await db.select({
  55. table: 'author',
  56. dirtyIdsOnly: true,
  57. });
  58. db.searchCache.authorIdsAll = [];
  59. for (const row of authorRows) {
  60. authorIds.add(row.id);
  61. db.searchCache.authorIdsAll.push(row.id);
  62. }
  63. } else {//оптимизация
  64. for (const id of db.searchCache.authorIdsAll) {
  65. authorIds.add(id);
  66. }
  67. }
  68. }
  69. const idsArr = [];
  70. idsArr.push(authorIds);
  71. //серии
  72. if (query.series && query.series !== '*') {
  73. const where = this.getWhere(query.series);
  74. const seriesRows = await db.select({
  75. table: 'series',
  76. map: `(r) => ({authorId: r.authorId})`,
  77. where
  78. });
  79. const ids = new Set();
  80. for (const row of seriesRows) {
  81. for (const id of row.authorId)
  82. ids.add(id);
  83. }
  84. idsArr.push(ids);
  85. }
  86. //названия
  87. if (query.title && query.title !== '*') {
  88. const where = this.getWhere(query.title);
  89. const titleRows = await db.select({
  90. table: 'title',
  91. map: `(r) => ({authorId: r.authorId})`,
  92. where
  93. });
  94. const ids = new Set();
  95. for (const row of titleRows) {
  96. for (const id of row.authorId)
  97. ids.add(id);
  98. }
  99. idsArr.push(ids);
  100. }
  101. //жанры
  102. if (query.genre) {
  103. const genres = query.genre.split(',');
  104. const ids = new Set();
  105. for (const g of genres) {
  106. const genreRows = await db.select({
  107. table: 'genre',
  108. map: `(r) => ({authorId: r.authorId})`,
  109. where: `@@indexLR('value', ${db.esc(g)}, ${db.esc(g)})`,
  110. });
  111. for (const row of genreRows) {
  112. for (const id of row.authorId)
  113. ids.add(id);
  114. }
  115. }
  116. idsArr.push(ids);
  117. }
  118. //языки
  119. if (query.lang) {
  120. const langs = query.lang.split(',');
  121. const ids = new Set();
  122. for (const l of langs) {
  123. const langRows = await db.select({
  124. table: 'lang',
  125. map: `(r) => ({authorId: r.authorId})`,
  126. where: `@@indexLR('value', ${db.esc(l)}, ${db.esc(l)})`,
  127. });
  128. for (const row of langRows) {
  129. for (const id of row.authorId)
  130. ids.add(id);
  131. }
  132. }
  133. idsArr.push(ids);
  134. }
  135. if (idsArr.length > 1)
  136. authorIds = utils.intersectSet(idsArr);
  137. //сортировка
  138. authorIds = Array.from(authorIds);
  139. authorIds.sort((a, b) => a - b);
  140. return authorIds;
  141. }
  142. async getAuthorIds(query) {
  143. const db = this.db;
  144. if (!db.searchCache)
  145. db.searchCache = {};
  146. let result;
  147. //сначала попробуем найти в кеше
  148. const q = query;
  149. const keyArr = [q.author, q.series, q.title, q.genre, q.lang];
  150. const keyStr = keyArr.join('');
  151. if (!keyStr) {//пустой запрос
  152. if (db.searchCache.authorIdsAll)
  153. result = db.searchCache.authorIdsAll;
  154. else
  155. result = await this.selectAuthorIds(query);
  156. } else {//непустой запрос
  157. const key = JSON.stringify(keyArr);
  158. const rows = await db.select({table: 'query_cache', where: `@@id(${db.esc(key)})`});
  159. if (rows.length) {//нашли в кеше
  160. await db.insert({
  161. table: 'query_time',
  162. replace: true,
  163. rows: [{id: key, time: Date.now()}],
  164. });
  165. result = rows[0].value;
  166. } else {//не нашли в кеше, ищем в поисковых таблицах
  167. result = await this.selectAuthorIds(query);
  168. await db.insert({
  169. table: 'query_cache',
  170. replace: true,
  171. rows: [{id: key, value: result}],
  172. });
  173. await db.insert({
  174. table: 'query_time',
  175. replace: true,
  176. rows: [{id: key, time: Date.now()}],
  177. });
  178. }
  179. }
  180. return result;
  181. }
  182. async search(query) {
  183. if (this.closed)
  184. throw new Error('DbSearcher closed');
  185. this.searchFlag++;
  186. try {
  187. const db = this.db;
  188. const authorIds = await this.getAuthorIds(query);
  189. const totalFound = authorIds.length;
  190. let limit = (query.limit ? query.limit : 100);
  191. limit = (limit > 1000 ? 1000 : limit);
  192. const offset = (query.offset ? query.offset : 0);
  193. //выборка найденных авторов
  194. let result = await db.select({
  195. table: 'author',
  196. map: `(r) => ({id: r.id, author: r.author})`,
  197. where: `@@id(${db.esc(authorIds.slice(offset, offset + limit))})`
  198. });
  199. return {result, totalFound};
  200. } finally {
  201. this.searchFlag--;
  202. }
  203. }
  204. async periodicCleanCache() {
  205. this.timer = null;
  206. const cleanInterval = 30*1000;//this.config.cacheCleanInterval*60*1000;
  207. try {
  208. const db = this.db;
  209. const oldThres = Date.now() - cleanInterval;
  210. //выберем всех кандидатов на удаление
  211. const rows = await db.select({
  212. table: 'query_time',
  213. where: `
  214. @@iter(@all(), (r) => (r.time < ${db.esc(oldThres)}));
  215. `
  216. });
  217. const ids = [];
  218. for (const row of rows)
  219. ids.push(row.id);
  220. //удаляем
  221. await db.delete({table: 'query_cache', where: `@@id(${db.esc(ids)})`});
  222. await db.delete({table: 'query_time', where: `@@id(${db.esc(ids)})`});
  223. //console.log('Cache clean', ids);
  224. } catch(e) {
  225. console.error(e.message);
  226. } finally {
  227. if (!this.closed) {
  228. this.timer = setTimeout(() => { this.periodicCleanCache(); }, cleanInterval);
  229. }
  230. }
  231. }
  232. async close() {
  233. while (this.searchFlag > 0) {
  234. await utils.sleep(50);
  235. }
  236. if (this.timer) {
  237. clearTimeout(this.timer);
  238. this.timer = null;
  239. }
  240. this.closed = true;
  241. }
  242. }
  243. module.exports = DbSearcher;