按日期对文件排序,按类型分组

时间:2019-09-12 15:52:00

标签: mapreduce couchdb pouchdb

我不知道如何编写地图/缩小功能以使所有类型的电影按照最新电影的日期排序。

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]}

1 个答案:

答案 0 :(得分:0)

我可能会反转索引字段的顺序。

以下是一些示例:

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))
  }