IBM Cloud Docs
ビューの使用

ビューの使用

ビューを使用して、データベース内で特定の基準に一致する内容を検索します。 基準はビュー定義内で指定します。

ビューの使用時に基準を引数として指定することもできます。

ビューの照会

ビューを照会するには、以下の形式で GET 要求を送信します。

メソッド
コマンド GET $SERVICE_URL/$DATABASE/_partition/$PARTITION_KEY/_design/$DDOC/_view/$VIEW_NAME を使用してパーティション照会を発行します。 または、コマンド GET $SERVICE_URL/$DATABASE/_design/$DDOC/_view/$VIEW_NAME を使用してグローバル照会を発行します。
要求
なし
応答
ビューによって返される文書の JSON。
許可される役割
_reader

要求により、以下のいずれかが実行されます。

  • 指定された $DDOC 設計文書からの $VIEW_NAME 指定された データベース内で $DATABASE 指定された $PARTITION_KEY data partition.
  • $DATABASE データベース内の指定された $DDOC 設計文書からの指定された $VIEW_NAME

この文書の例は、説明のために、パーティション照会とグローバル照会の間で異なります。 特に明記されていない限り、パーティション名を組み込むか削除するパスの変更は、どのビュー照会タイプでも機能します。

照会および JSON 本文の引数

グローバル照会では、すべての照会および JSON 本文の引数を使用できます。 パーティション照会では、表に示されているサブセットのみを使用できます。

パーティショニングされたクエリで使用可能なクエリおよびJSONボディ引数のサブセット
引数 説明 オプション タイプ デフォルト サポートされる値 パーティション照会
conflicts 競合するリビジョンのリストを、返されたドキュメントの _conflicts プロパティに含めるかどうかを指定する。 Ignored if include_docs isn't set to true. ある ブール値 いいえ ある
descending descending by key の順序でドキュメントを返しします。 ある ブール値 いいえ ある
end_key 指定されたキーに達したときに、レコードを返す処理を停止します。 ある ストリングまたは JSON 配列 ある
end_key_docid 指定された文書 ID に達したときに、レコードを返す処理を停止します。 ある ストリング ある
group 縮小された結果をキーごとにグループ化するかどうかを指定する。 ビューにリデュース関数が定義されている場合のみ有効。 ビューがJSON配列形式でキーを出力する場合、group_level パラメータで配列の要素数に基づいてさらにグループを減らすことが可能です。 ある ブール値 いいえ ある
group_level 使用するグループ・レベルを指定する。 ビューが JSON 配列のキーを使用する場合にのみ適用可能です。 グループが true であることを意味する。 グループ・レベルは、指定された配列要素数で縮小結果をグループ化します。 未設定の場合、結果は配列のキー全体でグループ化され、完全なキーごとに削減された値が返されます。 ある 数値 ある
include_docs 応答に、文書の内容全体を組み込みます。 ある ブール値 いいえ ある
inclusive_end 指定された end_key を持つ行を含めます。 ある ブール値 はい ある
key 指定されたキーに一致する文書のみを返します。 キーは JSON 値であり、URL でエンコードする必要があります。 ある JSON 配列 ある
keys 指定したキーのいずれかにマッチする文書のみを返すように指定する。 ビュー関数が出力するキーの型にマッチするキーの JSON 配列の文字列表現。 ある ストリングまたは JSON 配列 ある
limit 返される文書の数を指定されたカウントに制限します。 ある 数値 ある
reduce reduce 関数を使用します。 ある ブール値 はい ある
skip 先頭からこの行数をスキップします。 ある 数値 0 ある
stable 各リクエストでインデックスの同じレプリカを使用するかどうかを指定します。 デフォルト値は false すべてのレプリカにコンタクトし、最初の最も速いレスポンダからの結果を返します。 true 設定すると、update=false と一緒に使用した場合、選択されたレプリカが利用可能なレプリカの中で最速でない場合、待ち時間の増加とスループットの低下を犠牲にして一貫性が向上する可能性があります

:一般的に、update=true を使用する場合、このパラメータを true に設定することは推奨されない。

ある ブール値 いいえ いいえ
stale

: stale is deprecated. 代わりに stableupdate を使う

Specify whether to use the results from a stale view without triggering a rebuild of all views within the encompassing design doc.

  • ok is equivalent to stable=true&update=false.
  • update_after is equivalent to stable=true&update=lazy.
ある ストリング いいえ いいえ
start_key 指定したキーからレコードを返します。 ある ストリングまたは JSON 配列 ある
start_key_docid 指定した文書 ID からレコードを返します。 ある ストリング ある
update

Specify whether or not the view in question must be updated before you respond to the user.

  • true- Return results after the view is updated.
  • false- Return results without updating the view.
  • lazy- Return the view results without waiting for an update, but update them immediately after the request.
ある ストリング はい ある

include_docs=true を使用すると、パフォーマンスへの影響が生じる可能性があります。

ユーザーが作成したビューを適用して、データベースのパーティションからドキュメントの全内容を含む最初の10個のドキュメントのリストを取得するためにHTTPを使用する例を参照してください。

GET $SERVICE_URL/$DATABASE/_partition/$PARTITION_KEY/_design/$DDOC/_view/$VIEW_NAME?include_docs=true&limit=10 HTTP/1.1

次は、ユーザー作成のビューを適用し、HTTP を使用して、データベースから最初の 10 個の文書のリストを取得する例です。

GET $SERVICE_URL/$DATABASE/_design/$DDOC/_view/$VIEW_NAME?limit=10 HTTP/1.1

ユーザが作成した byApplianceProdId ビューを適用して、データベースの small-appliances パーティションから、最初の10個のドキュメントの全内容を含むリストを取得する例を参照してください。

クライアント・ライブラリーは、GET の代わりに POST メソッドを使用する。

curl -X GET "$SERVICE_URL/products/_partition/small-appliances/_design/appliances/_view/byApplianceProdId?include_docs=true&limit=10"
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostPartitionViewOptions;
import com.ibm.cloud.cloudant.v1.model.ViewResult;

Cloudant service = Cloudant.newInstance();

PostPartitionViewOptions viewOptions =
    new PostPartitionViewOptions.Builder()
        .db("products")
        .ddoc("appliances")
        .includeDocs(true)
        .limit(10)
        .partitionKey("small-appliances")
        .view("byApplianceProdId")
        .build();

ViewResult response =
    service.postPartitionView(viewOptions).execute()
        .getResult();

System.out.println(response);
const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

service.postPartitionView({
  db: 'products',
  ddoc: 'appliances',
  includeDocs: true,
  limit: 10,
  partitionKey: 'small-appliances',
  view: 'byApplianceProdId'
}).then(response => {
  console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance()

response = service.post_partition_view(
  db='products',
  ddoc='appliances',
  include_docs=True,
  limit=10,
  partition_key='small-appliances',
  view='byApplianceProdId'
).get_result()

print(response)
postPartitionViewOptions := service.NewPostPartitionViewOptions(
  "products",
  "small-appliances",
  "appliances",
  "byApplianceProdId",
)
postPartitionViewOptions.SetIncludeDocs(true)
postPartitionViewOptions.SetLimit(10)

viewResult, response, err := service.PostPartitionView(postPartitionViewOptions)
if err != nil {
  panic(err)
}

b, _ := json.MarshalIndent(viewResult, "", "  ")
fmt.Println(string(b))

前の Go の例では、以下のインポート・ブロックが必要です。

import (
   "encoding/json"
   "fmt"
   "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

すべての Go の例では、serviceオブジェクトを初期化する必要があります。 詳しくは、API 資料の認証セクションで例を参照してください。

次は、ユーザー作成の getVerifiedEmails ビューを適用して、データベースから最初の 10 個の文書のリストを取得する例です。

クライアント・ライブラリーは、GET の代わりに POST メソッドを使用する。

curl -X GET "$SERVICE_URL/users/_design/allusers/_view/getVerifiedEmails?limit=10"
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostViewOptions;
import com.ibm.cloud.cloudant.v1.model.ViewResult;

Cloudant service = Cloudant.newInstance();

PostViewOptions viewOptions = new PostViewOptions.Builder()
    .db("users")
    .ddoc("allusers")
    .view("getVerifiedEmails")
    .limit(10)
    .build();

ViewResult response =
    service.postView(viewOptions).execute()
        .getResult();

System.out.println(response);
const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

service.postView({
  db: 'users',
  ddoc: 'allusers',
  view: 'getVerifiedEmails',
  limit: 10
}).then(response => {
  console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance()

response = service.post_view(
  db='users',
  ddoc='allusers',
  view='getVerifiedEmails',
  limit=10
).get_result()

print(response)
postViewOptions := service.NewPostViewOptions(
  "users",
  "allusers",
  "getVerifiedEmails",
)

postViewOptions.SetLimit(10)

viewResult, response, err := service.PostView(postViewOptions)
if err != nil {
  panic(err)
}

b, _ := json.MarshalIndent(viewResult, "", "  ")
fmt.Println(string(b))

前の Go の例では、以下のインポート・ブロックが必要です。

import (
   "encoding/json"
   "fmt"
   "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

すべての Go の例では、serviceオブジェクトを初期化する必要があります。 詳しくは、API 資料の認証セクションで例を参照してください。

要求に対する応答の例を以下に示します。

{
  "offset": 0,
  "rows": [
    {
      "id": "abc125",
      "key": "amelie.smith@aol.com",
      "value": [
        "Amelie Smith",
        true,
        "2020-04-24T10:42:59.000Z"
      ]
    },
    {
      "id": "abc123",
      "key": "bob.smith@aol.com",
      "value": [
        "Bob Smith",
        true,
        "2019-01-24T10:42:59.000Z"
      ]
    }
  ],
  "total_rows": 2
}

索引

ビューが設計文書で定義されると、ビュー内に定義されている情報に基づいて、対応する索引も作成されます。 索引を使用して、 _id フィールド以外の基準で文書を検索します。 例えば、フィールド、フィールドの組み合わせ、または文書の内容を使用して計算された値によって選択できます。 索引には、設計文書が作成されるとすぐにデータが取り込まれます。 大規模なデータベースでは、このプロセスに時間がかかることがあります。

以下のイベントのいずれかが発生した場合、インデックスの内容はインクリメンタルに自動的に更新されます:

  • 新しい文書がデータベースに追加されます。
  • 既存の文書がデータベースから削除されます。
  • データベース内の既存の文書が更新されます。

ビュー定義が変更されるか、同じ設計文書内の別のビュー定義が変更されると、ビュー索引は完全に再作成されます。 再作成により、ビュー定義に対する変更がビュー索引に反映されます。 再作成が確実に行われるようにするために、設計文書が更新されるたびにビュー定義の「指紋」が作成されます。 指紋が変更されると、ビュー索引が再作成されます。

ビュー索引は、設計文書に定義されているすべてのビューのうちいずれかのビューを変更すると、再作成されます。 例えば、3 つのビューを含む設計文書がある場合に設計文書を更新すると、設計文書内の 3 つすべてのビュー索引が再作成されます。 より大規模なデータベースの設計文書を変更する場合は、設計文書の管理ガイドを参照してください。

データベースが最近更新された場合、ビューにアクセスすると結果が遅延する可能性があります。 遅延は、データベースに対する変更の数、およびデータベースの内容が変更されたためにビュー索引が最新でないかどうかによって影響を受けます。

これらの遅延をなくすことはできません。 新しく作成されたデータベースの場合、文書を挿入または更新する前に、データベース内の設計文書にビュー定義を作成することにより、遅延を削減することができます。 設計文書にビュー定義を作成すると、文書の挿入時に、索引に対して増分更新が実行されます。

応答速度のほうがデータを最新に保つことよりも重要な場合は、代わりに、ユーザーが古いバージョンのビュー索引にアクセスできるようにすることもできます。 古いバージョンのビュー索引にアクセスできるようにするには、ビュー照会を行うときに update 照会ストリング・パラメーターを使用します。

索引付けプロセッサーを使用せずに古い索引バージョンを保存する場合は、"autoupdate": {"indexes": false} を設定して、すべての索引が作成されないようにすることができます。 または、以下のいずれかのオプションを設計文書に追加して、ビューが自動更新されないようにすることもできます。 "autoupdate": false を設定すると、すべての索引タイプが索引付けされないようにすることができます。

以下の例を参照してください。

{
  "_id": "_design/lookup",
  "autoupdate": false,
  "views": {
    "view": {
      "map": "function(doc)..."
    }
  }
}
{
  "_id": "_design/lookup",
  "autoupdate": {"views": false},
  "views": {
    "view": {
      "map": "function(doc)..."
    }
  }
}

ビューの最新性

デフォルトでは、すべての索引結果にデータベースの現在の状態が反映されます。 IBM Cloudant は、バックグラウンドで索引を自動的かつ非同期的に作成します。 この方法は は通常、クエリ時にインデックスが完全に最新であることを意味する。 もし デフォルトでは、IBM Cloudantはクエリ時に残りの更新を適用します。 を適用します。

IBM Cloudantにはいくつかのパラメータがあります、 この動作を変更するために、次に説明するいくつかのパラメータを提供します。 を使用しないことを推奨する。 通常、副作用がその利点を上回るからである。

パラメーター

update オプションは、ビューの更新を待機せずにビュー結果を受け入れる準備ができているかどうかを示します。 デフォルト値は true で、結果を返す前にビューが更新されることを意味します。 lazy 値は、ビューの更新前に結果を返すが、その後、いずれにしてもビューを更新する必要があることを意味します。

IBM Cloudantは以下のように努めています。 はバックグラウンドでインデックスを更新し続けるように努めていますが、*や でクエリされた時にビューがどの程度古くなっているかについての update=false はありません。 update=lazy.

stable オプションは、単一の整合したシャードのセットから結果を取得するかどうかを示します。 false 値は すべての利用可能なシャード・レプリカが照会され IBM Cloudantは最速のレスポンスを使用します。 レスポンスを使用します。 対照的に stable=true forces the database to use just one replica of the index.

stable=true 使用するとレイテンシーが大きくなることがある。 を使用すると、たとえ他のコピーの方が速く応答できるとしても、 インデックスのコピーの1つだけを参照するため、待ち時間が長くなります。 を使用すると、たとえ他のコピーの方が速く応答したとしても、 インデックスのコピーの1つだけを参照するため、待ち時間が長くなります。

パラメーターの結合

If you specify stable=false and update=false, you see greater inconsistency between results, even for the same query and without making database changes. システムがこの動作に耐えられると確信できる場合以外は、この組み合わせは避けることをお勧めします。 システムがこの動作に耐えられると確信していない限り、この組み合わせは避けることをお勧めします。

返された行のソート

ビュー照会によって返されるデータは、配列の形式です。 配列内の各要素は、標準の UTF-8ソートされます。 ソートは、ビュー関数で定義されたキーに適用されます。

以下の表に、出力の基本的な順序を示します。

返された行の順序
順序
null 1 番目
false
true
数値
テキスト (小文字)
テキスト (大文字)
配列 (この表に示されている順序を使用した、各要素の値による)
オブジェクト (この表に示されている順序を使用した、キー順序におけるキーの値による) 最後

返されるビュー情報の順序を逆にするには、descending 照会値を true に設定します。

keys パラメーターを指定するビュー要求を実行する場合、結果は、指定された keys 配列と同じ順序で返されます。

次は、HTTP を使用して、逆のソート順でレコードを要求する例です。

GET $SERVICE_URL/$DATABASE/_design/$DDOC/_view/$VIEW_NAME?descending=true HTTP/1.1
Accept: application/json

次は、逆のソート順でレコードを要求する例です。

クライアント・ライブラリーは、GET の代わりに POST メソッドを使用します。これは、これらのメソッドが同様の動作をするためです。

curl -X GET "$SERVICE_URL/users/_design/allusers/_view/getVerifiedEmails?descending=true"
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostViewOptions;
import com.ibm.cloud.cloudant.v1.model.ViewResult;

Cloudant service = Cloudant.newInstance();

PostViewOptions viewOptions = new PostViewOptions.Builder()
    .db("users")
    .ddoc("allusers")
    .view("getVerifiedEmails")
    .descending(true)
    .build();

ViewResult response =
    service.postView(viewOptions).execute()
        .getResult();

System.out.println(response);
const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

service.postView({
  db: 'users',
  ddoc: 'allusers',
  view: 'getVerifiedEmails',
  descending: true
}).then(response => {
  console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance()

response = service.post_view(
  db='users',
  ddoc='allusers',
  view='getVerifiedEmails',
  descending=True
).get_result()

print(response)
postViewOptions := service.NewPostViewOptions(
  "users",
  "allusers",
  "getVerifiedEmails",
)

postViewOptions.SetDescending(true)

viewResult, response, err := service.PostView(postViewOptions)
if err != nil {
  panic(err)
}

b, _ := json.MarshalIndent(viewResult, "", "  ")
fmt.Println(string(b))

前の Go の例では、以下のインポート・ブロックが必要です。

import (
   "encoding/json"
   "fmt"
   "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

すべての Go の例では、serviceオブジェクトを初期化する必要があります。 詳しくは、API 資料の認証セクションで例を参照してください。

次は、レコードを逆のソート順で要求する場合の応答の例です。

{
  "total_rows": 2,
  "offset": 0,
  "rows": [
    {
      "id": "abc123",
      "key": "bob.smith@aol.com",
      "value": [
        "Bob Smith",
        true,
        "2019-01-24T10:42:59.000Z"
      ]
    },
    {
      "id": "abc125",
      "key": "amelie.smith@aol.com",
      "value": [
        "Amelie Smith",
        true,
        "2020-04-24T10:42:59.000Z"
      ]
    }
  ]
}

開始キーと終了キーの指定

start_key および end_key の各照会引数を使用して、ビューの照会時に返される値の範囲を指定できます。

ソート方向は、常に最初に適用されます。 次に、 start_key および end_key の各照会引数を使用して、フィルタリングが適用されます。 ソートプランとフィルタープランの組み合わせが意味をなさない場合、キーレンジに一致する行がない可能性があります。

See the example of using HTTP to make a global query that includes start_key and end_key クエリーの引数:

GET $SERVICE_URL/$DATABASE/_design/$DDOC/_view/$VIEW_NAME?start_key="alpha"&end_key="beta" HTTP/1.1

次は、start_key および end_key の各照会引数を含むグローバル照会の例です。

クライアント・ライブラリーは、GET の代わりに POST メソッドを使用する。

curl -X GET "$SERVICE_URL/users/_design/allusers/_view/getVerifiedEmails?start_key=\"alpha\"&end_key=\"beta\""
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostViewOptions;
import com.ibm.cloud.cloudant.v1.model.ViewResult;

Cloudant service = Cloudant.newInstance();

PostViewOptions viewOptions = new PostViewOptions.Builder()
    .db("users")
    .ddoc("allusers")
    .view("getVerifiedEmails")
    .startKey("alpha")
    .endKey("beta")
    .build();

ViewResult response =
    service.postView(viewOptions).execute()
        .getResult();

System.out.println(response);
const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

service.postView({
  db: 'users',
  ddoc: 'allusers',
  view: 'getVerifiedEmails',
  startKey: 'alpha',
  endKey: 'beta'
}).then(response => {
  console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance()

response = service.post_view(
  db='users',
  ddoc='allusers',
  view='getVerifiedEmails',
  start_key='alpha',
  end_key='beta'  
).get_result()

print(response)
postViewOptions := service.NewPostViewOptions(
  "users",
  "allusers",
  "getVerifiedEmails",
)

postViewOptions.StartKey = "alpha"
postViewOptions.EndKey = "beta"

viewResult, response, err := service.PostView(postViewOptions)
if err != nil {
  panic(err)
}

b, _ := json.MarshalIndent(viewResult, "", "  ")
fmt.Println(string(b))

前の Go の例では、以下のインポート・ブロックが必要です。

import (
   "encoding/json"
   "fmt"
   "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

すべての Go の例では、serviceオブジェクトを初期化する必要があります。 詳しくは、API 資料の認証セクションで例を参照してください。

例えば、alphastart_key を使用すると1つの結果を返すデータベースがあるとする and an end_key of beta, you would get a 400 (Bad request) error with a reversed order. これは、キー・フィルターが適用される前に、ビュー内の項目が反転されるためです。

See the example that uses HTTP to illustrate why reversing the order of start_key and end_key はクエリ・パース・エラーを返すかもしれません:

GET $SERVICE_URL/$DATABASE/_design/$DDOC/_view/$VIEW_NAME?descending=true&start_key="alpha"&end_key="beta" HTTP/1.1

次は、start_keyend_key の順序を逆にすると 400 エラーが発生する可能性がある理由を示す例です。

クライアント・ライブラリーは、GET の代わりに POST メソッドを使用する。

curl -X GET "$SERVICE_URL/users/_design/allusers/_view/getVerifiedEmails?descending=true&start_key=\"alpha\"&end_key=\"beta\""
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostViewOptions;
import com.ibm.cloud.cloudant.v1.model.ViewResult;

Cloudant service = Cloudant.newInstance();

PostViewOptions viewOptions = new PostViewOptions.Builder()
    .db("users")
    .ddoc("allusers")
    .view("getVerifiedEmails")
    .descending(true)
    .startKey("alpha")
    .endKey("beta")
    .build();

ViewResult response =
    service.postView(viewOptions).execute()
        .getResult();

System.out.println(response);
const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

service.postView({
  db: 'users',
  ddoc: 'allusers',
  view: 'getVerifiedEmails',
  descending: true,
  startKey: 'alpha',
  endKey: 'beta'
}).then(response => {
  console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance()

response = service.post_view(
  db='users',
  ddoc='allusers',
  view='getVerifiedEmails',
  descending=True,  
  start_key='alpha',
  end_key='beta'  
).get_result()

print(response)
postViewOptions := service.NewPostViewOptions(
  "users",
  "allusers",
  "getVerifiedEmails",
)

postViewOptions.SetDescending(true)
postViewOptions.StartKey = "alpha"
postViewOptions.EndKey = "beta"

viewResult, response, err := service.PostView(postViewOptions)
if err != nil {
  panic(err)
}

b, _ := json.MarshalIndent(viewResult, "", "  ")
fmt.Println(string(b))

前の Go の例では、以下のインポート・ブロックが必要です。

import (
   "encoding/json"
   "fmt"
   "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

すべての Go の例では、serviceオブジェクトを初期化する必要があります。 詳しくは、API 資料の認証セクションで例を参照してください。

betaend_key が、alphastart_key の前に表示され、照会構文解析エラーが発生します。

解決策は、ソート順だけでなく、start_key パラメーター値と end_key パラメーター値も反転することです。

次の例では、descending 照会引数を使用して、start_key および end_key の各照会引数を反転することにより、出力の順序を適切にフィルタリングおよび反転します。

HTTP を使用して、適切なフィルタリングおよびソートをグローバル照会に適用する例を以下に示します。

GET $SERVICE_URL/$DATABASE/_design/$DDOC/_view/$VIEW_NAME?descending=true&start_key="beta"&end_key="alpha" HTTP/1.1

次は、適切なフィルタリングおよびソートをグローバル照会に適用する例です。

クライアント・ライブラリーは、GET の代わりに POST メソッドを使用する。

curl -X GET "$SERVER_URL/users/_design/allusers/_view/getVerifiedEmails?descending=true&start_key=\"beta\"&end_key=\"alpha\""
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostViewOptions;
import com.ibm.cloud.cloudant.v1.model.ViewResult;

Cloudant service = Cloudant.newInstance();

PostViewOptions viewOptions = new PostViewOptions.Builder()
    .db("users")
    .ddoc("allusers")
    .view("getVerifiedEmails")
    .descending(true)
    .startKey("beta")
    .endKey("alpha")
    .build();

ViewResult response =
    service.postView(viewOptions).execute()
        .getResult();

System.out.println(response);
const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

service.postView({
  db: 'users',
  ddoc: 'allusers',
  view: 'getVerifiedEmails',
  descending: true,
  startKey: 'beta',
  endKey: 'alpha'
}).then(response => {
  console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance()

response = service.post_view(
  db='users',
  ddoc='allusers',
  view='getVerifiedEmails',
  descending=True,  
  start_key='beta',
  end_key='alpha'  
).get_result()

print(response)
postViewOptions := service.NewPostViewOptions(
  "users",
  "allusers",
  "getVerifiedEmails",
)

postViewOptions.SetDescending(true)
postViewOptions.StartKey = "beta"
postViewOptions.EndKey = "alpha"

viewResult, response, err := service.PostView(postViewOptions)
if err != nil {
  panic(err)
}

b, _ := json.MarshalIndent(viewResult, "", "  ")
fmt.Println(string(b))

前の Go の例では、以下のインポート・ブロックが必要です。

import (
   "encoding/json"
   "fmt"
   "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

すべての Go の例では、serviceオブジェクトを初期化する必要があります。 詳しくは、API 資料の認証セクションで例を参照してください。

キーのリストを使用したビューの照会

使用するキーのリストを指定して、照会を実行することもできます。

この方法でデータベースからの情報を要求する場合、指定された $DDOC 設計文書からの指定された $VIEW_NAME が使用されます。 GET メソッドの keys パラメーターと同様に、POST メソッドを使用して、ビュー結果の取得に使用するキーを指定できます。 その他すべての側面において、 POST メソッドは、GET API 要求と同じです。 特に、照会ストリングまたは JSON 本文のいずれかで、その照会パラメーターのいずれかを使用できます。

次は、すべてのユーザーを返す HTTP 要求 (ビューのキーが amelie.smith@aol.com または bob.smith@aol.com のいずれかに一致する) の例です。

POST $SERVICE_URL/$DATABASE/_design/$DDOC/_view/$VIEW_NAME HTTP/1.1
Content-Type: application/json

{
  "keys": [
    "amelie.smith@aol.com",
    "bob.smith@aol.com"
  ]
}

See the example of a global query that returns all users (where the key for the view matches is either amelie.smith@aol.com or bob.smith@aol.com):

curl -X POST "$SERVICE_URL/users/_design/allusers/_view/getVerifiedEmails" -H "Content-Type: application/json" --data '{
  "keys": [
    "amelie.smith@aol.com",
    "bob.smith@aol.com"
  ]
}'
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostViewOptions;
import com.ibm.cloud.cloudant.v1.model.ViewResult;

import java.util.Arrays;

Cloudant service = Cloudant.newInstance();

PostViewOptions viewOptions = new PostViewOptions.Builder()
    .db("users")
    .ddoc("allusers")
    .view("getVerifiedEmails")
    .keys(Arrays.asList("amelie.smith@aol.com", "bob.smith@aol.com"))
    .build();

ViewResult response =
    service.postView(viewOptions).execute()
        .getResult();

System.out.println(response);
const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

service.postView({
  db: 'users',
  ddoc: 'allusers',
  view: 'getVerifiedEmails',
  keys: ['amelie.smith@aol.com', 'bob.smith@aol.com']
}).then(response => {
  console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance()

response = service.post_view(
  db='users',
  ddoc='allusers',
  view='getVerifiedEmails',
  keys=['amelie.smith@aol.com', 'bob.smith@aol.com']
).get_result()

print(response)
postViewOptions := service.NewPostViewOptions(
  "users",
  "allusers",
  "getVerifiedEmails",
)

keys := []interface{}{"amelie.smith@aol.com", "bob.smith@aol.com"}
postViewOptions.SetKeys(keys)

viewResult, response, err := service.PostView(postViewOptions)
if err != nil {
  panic(err)
}

b, _ := json.MarshalIndent(viewResult, "", "  ")
fmt.Println(string(b))

前の Go の例では、以下のインポート・ブロックが必要です。

import (
   "encoding/json"
   "fmt"
   "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

すべての Go の例では、serviceオブジェクトを初期化する必要があります。 詳しくは、API 資料の認証セクションで例を参照してください。

応答には、標準のビュー情報が含まれますが、キーが一致する文書に限定されます。

キーのリストを使用して照会を実行した後の応答の例を以下に示します。

{
  "total_rows": 2,
  "offset": 0,
  "rows": [
    {
      "id": "abc125",
      "key": "amelie.smith@aol.com",
      "value": [
        "Amelie Smith",
        true,
        "2020-04-24T10:42:59.000Z"
      ]
    },
    {
      "id": "abc123",
      "key": "bob.smith@aol.com",
      "value": [
        "Bob Smith",
        true,
        "2019-01-24T10:42:59.000Z"
      ]
    }
  ]
}

複数文書の取り出し

次のセクションでは、データベースから多くの文書への POST リクエストを取り上げます。

クライアント・アプリケーションの場合、この手法は、複数の GET API 要求を使用するのよりも効果的です。

ただし、include_docs=true では、それ自体のビューにアクセスする場合と比較して、追加の処理時間が必要になることがあります。

これは、ビュー照会で include_docs=true を使用することにより、クライアント・アプリケーションの応答を構成するために、すべての結果文書の取得が必要になるためです。 実際に、一連の文書すべての GET 要求が実行され、各要求は、他のアプリケーション要求とリソースを求めて競合します。

この影響を軽減する 1 つの方法は、ビュー索引ファイルから直接結果を取得することです。 include_docs=true を省略して、ビュー索引ファイルから直接結果を取得します。 代わりに、設計文書のマップ関数で、ビュー索引の値として必要なフィールドを出力します。

例えば、マップ関数で、以下の設計仕様を使用できます。

function(user) {
  if(user.email_verified === true) {
    emit(user.email, {name: user.name, email_verified: user.email_verified, joined: user.joined});
  }
}

次は、HTTP を使用して、パーティション内のリストされたキーと一致する文書の全コンテンツを取得する要求の例です。

POST $SERVICE_URL/$DATABASE/_partition/$PARTITION_KEY/_design/$DDOC/_view/$VIEW_NAME HTTP/1.1
Content-Type: application/json

{
  "include_docs": true,
  "keys" : [
    "1000043",
    "1000044"
  ]
}

次は、products パーティション内のリストされたキーと一致する文書の全コンテンツを取得する要求の例です。

curl -X POST "$SERVICE_URL/products/_partition/small-appliances/_design/appliances/_view
/byApplianceProdId" -H "Content-Type: application/json" --data '{
  "include_docs": true,
  "keys" : [
    "1000043",
    "1000044"
  ]
}'
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.PostPartitionViewOptions;
import com.ibm.cloud.cloudant.v1.model.ViewResult;

import java.util.Arrays;

Cloudant service = Cloudant.newInstance();

PostPartitionViewOptions viewOptions =
    new PostPartitionViewOptions.Builder()
        .db("products")
        .ddoc("appliances")
        .keys(Arrays.asList("1000043", "1000044"))
        .includeDocs(true)
        .partitionKey("small-appliances")
        .view("byApplianceProdId")
        .build();

ViewResult response =
    service.postPartitionView(viewOptions).execute()
        .getResult();

System.out.println(response);
const { CloudantV1 } = require('@ibm-cloud/cloudant');

const service = CloudantV1.newInstance({});

service.postPartitionView({
  db: 'products',
  ddoc: 'appliances',
  keys: ['1000043', '1000044'],
  includeDocs: true,
  partitionKey: 'small-appliances',
  view: 'byApplianceProdId'
}).then(response => {
  console.log(response.result);
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance()

response = service.post_partition_view(
  db='products',
  ddoc='appliances',
  keys=['1000043', '1000044'],
  include_docs=True,  
  partition_key='small-appliances',
  view='byApplianceProdId'
).get_result()

print(response)
postPartitionViewOptions := service.NewPostPartitionViewOptions(
  "products",
  "small-appliances",
  "appliances",
  "byApplianceProdId",
)

keys := []interface{}{"1000043", "1000044"}
postPartitionViewOptions.SetKeys(keys)
postPartitionViewOptions.SetIncludeDocs(true)

viewResult, response, err := service.PostPartitionView(postPartitionViewOptions)
if err != nil {
  panic(err)
}

b, _ := json.MarshalIndent(viewResult, "", "  ")
fmt.Println(string(b))

前の Go の例では、以下のインポート・ブロックが必要です。

import (
   "encoding/json"
   "fmt"
   "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

すべての Go の例では、serviceオブジェクトを初期化する必要があります。 詳しくは、API 資料の認証セクションで例を参照してください。

次は、指定されたキーと一致する各アプライアンスの文書全体を返す (省略された) 応答の例です。

{
  "total_rows": 4,
  "offset": 1,
  "rows": [
    {
      "id": "small-appliances:1000043",
      "key": "1000043",
      "value": [
        "Bar",
        "Pro",
        "A professional, high powered innovative tool with a sleek design and outstanding performance"
      ],
      "doc": {
        "_id": "small-appliances:1000043",
        "_rev": "2-b595c929aabc3ab13415cd0cc03e665d",
        "type": "product",
        "taxonomy": [
          "Home",
          "Kitchen",
          "Small Appliances"
        ],
        "keywords": [
          "Bar",
          "Blender",
          "Kitchen"
        ],
        "productId": "1000043",
        "brand": "Bar",
        "name": "Pro",
        "description": "A professional, high powered innovative tool with a sleek design and outstanding performance",
        "colours": [
          "black"
        ],
        "price": 99.99,
        "image": "assets/img/barpro.jpg"
      }
    },
    {
      "id": "small-appliances:1000044",
      "key": "1000044",
      "value": [
        "Baz",
        "Omelet Maker",
        "Easily make delicious and fluffy omelets without flipping - Innovative design - Cooking and cleaning is easy"
      ],
      "doc": {
        "_id": "small-appliances:1000044",
        "_rev": "2-d54d022a9407ab9f06b1889cb2ab8a6e",
        "type": "product",
        "taxonomy": [
          "Home",
          "Kitchen",
          "Small Appliances"
        ],
        "keywords": [
          "Baz",
          "Maker",
          "Kitchen"
        ],
        "productId": "1000044",
        "brand": "Baz",
        "name": "Omelet Maker",
        "description": "Easily make delicious and fluffy omelets without flipping - Innovative design - Cooking and cleaning is easy",
        "colours": [
          "black"
        ],
        "price": 29.99,
        "image": "assets/img/bazomeletmaker.jpg"
      }
    }
  ]
}