search.js 8.2 KB

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