1

私は CouchDB (および一般的な NoSQL) の初心者であり、簡単な Node.js + Express + nano アプリを作成してその感触をつかんでいます。これは、'title' と 'author' の 2 つのフィールドを持つ単純な書籍のコレクションです。

文書例:

{
   "_id": "1223e03eade70ae11c9a3a20790001a9",
   "_rev": "2-2e54b7aa874059a9180ac357c2c78e99",
   "title": "The Art of War",
   "author": "Sun Tzu"
}

縮小機能:

function(doc) {
  if (doc.title && doc.author) {
    emit(doc.title, doc.author);
  }
}

CouchDB はキーでソートし、'descending=true' クエリ パラメータをサポートしているため、タイトルのソート順を切り替えるフィルタを UI に実装するのは簡単でした。これが結果セットのキーです。UI は次のとおりです。

昇順または降順でタイトルを並べ替えるためのリンク付きの書籍のリスト

しかし、私は著者フィールドに対してこれを行う方法について完全に途方に暮れています。

私はこの質問を見てきました。これは、投稿者が数値のreduce値でソートするのに役立ちました。また、リストを使用してreduce値でソートするブログ投稿も読みましたが、これを行う方法は見たことがありませんreduce のない文字列値。

4

1 に答える 1

2

If you want to sort by a particular property, you need to ensure that that property is the key (or, in the case of an array key, the first element in the array).

I would recommend using the sort key as the key, emitting a null value and using include_docs to fetch the full document to allow you to display multiple properties in the UI (this also keeps the deserialized value consistent so you don't need to change how you handle the return value based on sort order).

Your map functions would be as simple as the following.

For sorting by author:

function(doc) {
  if (doc.title && doc.author) {
    emit(doc.author, null);
  }
}

For sorting by title:

function(doc) {
  if (doc.title && doc.author) {
    emit(doc.title, null);
  }
}

Now you just need to change which view you call based on the selected sort order and ensure you use the include_docs=true parameter on your query.

You could also use a single view for this by emitting both at once...

emit(["by_author", doc.author], null);
emit(["by_title", doc.title], null);

... and then using the composite key for your query.

于 2015-10-27T10:32:59.300 に答える