【问题标题】:Sort documents by date and group by type按日期排序文档并按类型分组
【发布时间】:2019-09-12 15:52:00
【问题描述】:

我不知道如何编写 map/reduce 函数来让所有电影类型按最新电影的日期排序。

async function test() {
  const db = new PouchDB("film")

  const docs = [
    { _id: "1", title: "Rambo", year: 2008, genre: "Action" },
    { _id: "2", title: "Forrest Gump", year: 1994, genre: "Drama" },
    { _id: "3", title: "Gladiator", year: 2000, genre: "Action" },
    { _id: "4", title: "The Mask", year: 1994, genre: "Comedy" }
  ]
  await db.bulkDocs(docs)

  const fan = {
    map(doc) {
      emit([doc.year, doc.genre])
    },
    reduce(keys, values, rereduce) {
      return values
    }
  }

  const result = await db.query(fan, { group: true })
  result.rows.forEach(r => console.log(r))
}

返回:

{key: [1994, "Comedy"], value: [null]}
{key: [1994, "Drama"], value: [null]}
{key: [2000, "Action"], value: [null]}
{key: [2008, "Action"], value: [null]}

【问题讨论】:

    标签: mapreduce couchdb pouchdb


    【解决方案1】:

    我可能会颠倒索引字段的顺序。

    这里有一些例子:

    async function test() {
        const db = new PouchDB("film");
    
        const docs = [
          { _id: "1", title: "Rambo", year: 2008, genre: "Action" },
          { _id: "2", title: "Forrest Gump", year: 1994, genre: "Drama" },
          { _id: "3", title: "Gladiator", year: 2000, genre: "Action" },
          { _id: "4", title: "The Mask", year: 1994, genre: "Comedy" }
        ];
    
        await db.bulkDocs(docs);
    
        const fan = {
          map: function(doc) {
            emit([doc.genre, doc.year])
          },
          reduce: '_count'
        };
        // Get the view output
        const result = await db.query(fan, {
            reduce: false,
            include_docs: true
        })
    
        // Get a certain group
        const actionFilms = await db.query(fan, {
            startkey: ["Action"],
            endkey: ["Action", {}],
            reduce: false,
            include_docs: true
        });
    
        // Get the list of groups
        const genres = await db.query(fan, {
            group: true,
            group_level: 1
        });
    
        // Get the most recent value of a group
        const lastActionFilm = await db.query(fan, {
            startkey: ["Action", {}],
            endkey: ["Action"],
            reduce: false,
            descending: true,
            limit: 1,
            include_docs: true
        });
    
        result.rows.forEach(r => console.log(r))
      }
    

    【讨论】:

    • 以及如何按最新电影的日期对所有电影类型进行排序?
    • 喜欢:动作 -> 2008 ?
    • 您需要使用reduce 函数来保持最高值。请参阅此示例:stackoverflow.com/a/10390831/5236185
    猜你喜欢
    • 2015-11-25
    • 2016-04-10
    • 1970-01-01
    • 2011-02-19
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 2023-03-27
    相关资源
    最近更新 更多