search.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /**
  2. * Search
  3. */
  4. var elasticsearch = require('elasticsearch'),
  5. debug = require('debug')('crowi:lib:search');
  6. function SearchClient(crowi, esUri) {
  7. this.DEFAULT_OFFSET = 0;
  8. this.DEFAULT_LIMIT = 50;
  9. this.esUri = esUri;
  10. this.crowi = crowi;
  11. var uri = this.parseUri(this.esUri);
  12. this.host = uri.host;
  13. this.index_name = uri.index_name;
  14. this.client = new elasticsearch.Client({
  15. host: this.host,
  16. requestTimeout: 5000,
  17. });
  18. this.registerUpdateEvent();
  19. this.mappingFile = crowi.resourceDir + 'search/mappings.json';
  20. }
  21. SearchClient.prototype.checkESVersion = function() {
  22. // TODO
  23. };
  24. SearchClient.prototype.registerUpdateEvent = function() {
  25. var pageEvent = this.crowi.event('page');
  26. pageEvent.on('create', this.syncPageCreated.bind(this))
  27. pageEvent.on('update', this.syncPageUpdated.bind(this))
  28. pageEvent.on('delete', this.syncPageDeleted.bind(this))
  29. };
  30. SearchClient.prototype.shouldIndexed = function(page) {
  31. // FIXME: Magic Number
  32. if (page.grant !== 1) {
  33. return false;
  34. }
  35. if (page.redirectTo !== null) {
  36. return false;
  37. }
  38. if (page.isDeleted()) {
  39. return false;
  40. }
  41. return true;
  42. };
  43. // BONSAI_URL is following format:
  44. // => https://{ID}:{PASSWORD}@{HOST}
  45. SearchClient.prototype.parseUri = function(uri) {
  46. var index_name = 'crowi';
  47. var host = uri;
  48. if (m = uri.match(/^(https?:\/\/[^\/]+)\/(.+)$/)) {
  49. host = m[1];
  50. index_name = m[2];
  51. }
  52. return {
  53. host,
  54. index_name,
  55. };
  56. };
  57. SearchClient.prototype.buildIndex = function(uri) {
  58. return this.client.indices.create({
  59. index: this.index_name,
  60. body: require(this.mappingFile)
  61. });
  62. };
  63. SearchClient.prototype.deleteIndex = function(uri) {
  64. return this.client.indices.delete({
  65. index: this.index_name,
  66. });
  67. };
  68. SearchClient.prototype.prepareBodyForUpdate = function(body, page) {
  69. if (!Array.isArray(body)) {
  70. throw new Error('Body must be an array.');
  71. }
  72. var command = {
  73. update: {
  74. _index: this.index_name,
  75. _type: 'pages',
  76. _id: page._id.toString(),
  77. }
  78. };
  79. var document = {
  80. doc: {
  81. path: page.path,
  82. body: page.revision.body,
  83. comment_count: page.commentCount,
  84. bookmark_count: 0, // todo
  85. like_count: page.liker.length || 0,
  86. updated_at: page.updatedAt,
  87. },
  88. doc_as_upsert: true,
  89. };
  90. body.push(command);
  91. body.push(document);
  92. };
  93. SearchClient.prototype.prepareBodyForCreate = function(body, page) {
  94. if (!Array.isArray(body)) {
  95. throw new Error('Body must be an array.');
  96. }
  97. var command = {
  98. index: {
  99. _index: this.index_name,
  100. _type: 'pages',
  101. _id: page._id.toString(),
  102. }
  103. };
  104. var document = {
  105. path: page.path,
  106. body: page.revision.body,
  107. username: page.creator.username,
  108. comment_count: page.commentCount,
  109. bookmark_count: 0, // todo
  110. like_count: page.liker.length || 0,
  111. created_at: page.createdAt,
  112. updated_at: page.updatedAt,
  113. };
  114. body.push(command);
  115. body.push(document);
  116. };
  117. SearchClient.prototype.prepareBodyForDelete = function(body, page) {
  118. if (!Array.isArray(body)) {
  119. throw new Error('Body must be an array.');
  120. }
  121. var command = {
  122. delete: {
  123. _index: this.index_name,
  124. _type: 'pages',
  125. _id: page._id.toString(),
  126. }
  127. };
  128. body.push(command);
  129. };
  130. SearchClient.prototype.addPages = function(pages)
  131. {
  132. var self = this;
  133. var body = [];
  134. pages.map(function(page) {
  135. self.prepareBodyForCreate(body, page);
  136. });
  137. debug('addPages(): Sending Request to ES', body);
  138. return this.client.bulk({
  139. body: body,
  140. });
  141. };
  142. SearchClient.prototype.updatePages = function(pages)
  143. {
  144. var self = this;
  145. var body = [];
  146. pages.map(function(page) {
  147. self.prepareBodyForUpdate(body, page);
  148. });
  149. debug('updatePages(): Sending Request to ES', body);
  150. return this.client.bulk({
  151. body: body,
  152. });
  153. };
  154. SearchClient.prototype.deletePages = function(pages)
  155. {
  156. var self = this;
  157. var body = [];
  158. pages.map(function(page) {
  159. self.prepareBodyForDelete(body, page);
  160. });
  161. debug('deletePages(): Sending Request to ES', body);
  162. return this.client.bulk({
  163. body: body,
  164. });
  165. };
  166. SearchClient.prototype.addAllPages = function()
  167. {
  168. var self = this;
  169. var offset = 0;
  170. var Page = this.crowi.model('Page');
  171. var cursor = Page.getStreamOfFindAll();
  172. var body = [];
  173. var counter = 0;
  174. return new Promise(function(resolve, reject) {
  175. cursor.on('data', function (doc) {
  176. if (!doc.creator || !doc.revision || !self.shouldIndexed(doc)) {
  177. debug('Skipped', doc.path);
  178. return ;
  179. }
  180. self.prepareBodyForCreate(body, doc);
  181. }).on('error', function (err) {
  182. // TODO: handle err
  183. debug('Error cursor:', err);
  184. }).on('close', function () {
  185. // all done
  186. // 最後に送信
  187. self.client.bulk({
  188. body: body,
  189. requestTimeout: Infinity,
  190. })
  191. .then(function(res) {
  192. debug('Reponse from es:', res);
  193. return resolve(res);
  194. }).catch(function(err) {
  195. debug('Err from es:', err);
  196. return reject(err);
  197. });
  198. });
  199. });
  200. };
  201. /**
  202. * search returning type:
  203. * {
  204. * meta: { total: Integer, results: Integer},
  205. * data: [ pages ...],
  206. * }
  207. */
  208. SearchClient.prototype.search = function(query)
  209. {
  210. var self = this;
  211. return new Promise(function(resolve, reject) {
  212. self.client.search(query)
  213. .then(function(data) {
  214. var result = {
  215. meta: {
  216. took: data.took,
  217. total: data.hits.total,
  218. results: data.hits.hits.length,
  219. },
  220. data: data.hits.hits.map(function(elm) {
  221. return {_id: elm._id, _score: elm._score};
  222. })
  223. };
  224. resolve(result);
  225. }).catch(function(err) {
  226. reject(err);
  227. });
  228. });
  229. };
  230. SearchClient.prototype.createSearchQuerySortedByUpdatedAt = function(option)
  231. {
  232. // getting path by default is almost for debug
  233. var fields = ['path', '_id'];
  234. if (option) {
  235. fields = option.fields || fields;
  236. }
  237. // default is only id field, sorted by updated_at
  238. var query = {
  239. index: this.index_name,
  240. type: 'pages',
  241. body: {
  242. fields: fields,
  243. sort: [{ updated_at: { order: 'desc'}}],
  244. query: {}, // query
  245. }
  246. };
  247. this.appendResultSize(query);
  248. return query;
  249. };
  250. SearchClient.prototype.createSearchQuerySortedByScore = function(option)
  251. {
  252. var fields = ['path', '_id'];
  253. if (option) {
  254. fields = option.fields || fields;
  255. }
  256. // sort by score
  257. var query = {
  258. index: this.index_name,
  259. type: 'pages',
  260. body: {
  261. fields: fields,
  262. sort: [ {_score: { order: 'desc'} }],
  263. query: {}, // query
  264. }
  265. };
  266. this.appendResultSize(query);
  267. return query;
  268. };
  269. SearchClient.prototype.appendResultSize = function(query, from, size)
  270. {
  271. query.from = from || this.DEFAULT_OFFSET;
  272. query.size = size || this.DEFAULT_LIMIT;
  273. };
  274. SearchClient.prototype.appendCriteriaForKeywordContains = function(query, keyword)
  275. {
  276. // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
  277. if (!query.body.query.bool) {
  278. query.body.query.bool = {};
  279. }
  280. if (!query.body.query.bool.must || !Array.isArray(query.body.query.must)) {
  281. query.body.query.bool.must = [];
  282. }
  283. query.body.query.bool.must.push({
  284. multi_match: {
  285. query: keyword,
  286. fields: [
  287. "path.ja^2", // ためしに。
  288. "body.ja"
  289. ],
  290. operator: "and"
  291. }
  292. });
  293. };
  294. SearchClient.prototype.appendCriteriaForPathFilter = function(query, path)
  295. {
  296. // query is created by createSearchQuerySortedByScore() or createSearchQuerySortedByUpdatedAt()
  297. if (!query.body.query.bool) {
  298. query.body.query.bool = {};
  299. }
  300. if (!query.body.query.bool.filter || !Array.isArray(query.body.query.bool.filter)) {
  301. query.body.query.bool.filter = [];
  302. }
  303. if (path.match(/\/$/)) {
  304. path = path.substr(0, path.length - 1);
  305. }
  306. query.body.query.bool.filter.push({
  307. wildcard: {
  308. "path.raw": path + "/*"
  309. }
  310. });
  311. };
  312. SearchClient.prototype.searchKeyword = function(keyword, option)
  313. {
  314. var from = option.offset || null;
  315. var query = this.createSearchQuerySortedByScore();
  316. this.appendCriteriaForKeywordContains(query, keyword);
  317. return this.search(query);
  318. };
  319. SearchClient.prototype.searchByPath = function(keyword, prefix)
  320. {
  321. // TODO path 名だけから検索
  322. };
  323. SearchClient.prototype.searchKeywordUnderPath = function(keyword, path, option)
  324. {
  325. var from = option.offset || null;
  326. var query = this.createSearchQuerySortedByScore();
  327. this.appendCriteriaForKeywordContains(query, keyword);
  328. this.appendCriteriaForPathFilter(query, path);
  329. if (from) {
  330. this.appendResultSize(query, from);
  331. }
  332. return this.search(query);
  333. };
  334. SearchClient.prototype.syncPageCreated = function(page, user)
  335. {
  336. debug('SearchClient.syncPageCreated', page.path);
  337. if (!this.shouldIndexed(page)) {
  338. return ;
  339. }
  340. this.addPages([page])
  341. .then(function(res) {
  342. debug('ES Response', res);
  343. })
  344. .catch(function(err){
  345. debug('ES Error', err);
  346. });
  347. };
  348. SearchClient.prototype.syncPageUpdated = function(page, user)
  349. {
  350. debug('SearchClient.syncPageUpdated', page.path);
  351. // TODO delete
  352. if (!this.shouldIndexed(page)) {
  353. this.deletePages([page])
  354. .then(function(res) {
  355. debug('deletePages: ES Response', res);
  356. })
  357. .catch(function(err){
  358. debug('deletePages:ES Error', err);
  359. });
  360. return ;
  361. }
  362. this.updatePages([page])
  363. .then(function(res) {
  364. debug('ES Response', res);
  365. })
  366. .catch(function(err){
  367. debug('ES Error', err);
  368. });
  369. };
  370. SearchClient.prototype.syncPageDeleted = function(page, user)
  371. {
  372. debug('SearchClient.syncPageDeleted', page.path);
  373. this.deletePages([page])
  374. .then(function(res) {
  375. debug('deletePages: ES Response', res);
  376. })
  377. .catch(function(err){
  378. debug('deletePages:ES Error', err);
  379. });
  380. return ;
  381. };
  382. module.exports = SearchClient;