index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. exports.main = async (event, context) => {
  3. /**
  4. * 根据搜索记录,设定时间间隔来归纳出热搜数据并存储在热搜表中
  5. */
  6. const SEARCHHOT = 'opendb-search-hot'; // 热搜数据库名称
  7. const SEARCHLOG = 'opendb-search-log'; // 搜索记录数据库名称
  8. const SEARCHLOG_timeZone = 604800000; // 归纳搜索记录时间间隔,毫秒数,默认为最近7天
  9. const SEARCHHOT_size = 10; // 热搜条数
  10. const DB = uniCloud.database();
  11. const DBCmd = DB.command;
  12. const $ = DB.command.aggregate;
  13. const SEARCHHOT_db = DB.collection(SEARCHHOT);
  14. const SEARCHLOG_db = DB.collection(SEARCHLOG);
  15. const timeEnd = Date.now() - SEARCHLOG_timeZone;
  16. let {
  17. data: searchHotData
  18. } = await SEARCHLOG_db
  19. .aggregate()
  20. .match({
  21. create_date: DBCmd.gt(timeEnd)
  22. })
  23. .group({
  24. _id: {
  25. 'content': '$content',
  26. },
  27. count: $.sum(1)
  28. })
  29. .replaceRoot({
  30. newRoot: $.mergeObjects(['$_id', '$$ROOT'])
  31. })
  32. .project({
  33. _id: false
  34. })
  35. .sort({
  36. count: -1
  37. })
  38. .end();
  39. let now = Date.now();
  40. searchHotData.map(item => {
  41. item.create_date = now;
  42. return item;
  43. }).slice(0, SEARCHHOT_size);
  44. // searchHotData = searchHotData.sort((a, b) => b.count - a.count).slice(0, SEARCHHOT_size);
  45. return searchHotData.length ? await SEARCHHOT_db.add(searchHotData) : ''
  46. };