使用視圖

使用視圖在資料庫中搜尋符合特定條件的內容。 標準在視圖定義中指定。

使用視圖時,也可以將條件作為參數提供。

查詢檢視

若要查詢視圖,請提交以下格式的 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 資料 分區。
  • 來自指定 $DDOC 設計文件的指定 $VIEW_NAME 位於 $DATABASE 資料庫中。

出於說明目的,本文檔中的範例在分區查詢和全域查詢之間有所不同。 除非另有說明,否則修改嵌入或刪除分區名稱的路徑適用於任何視圖查詢類型。

查詢和 JSON 正文參數

全域查詢可以使用所有查詢和 JSON 內文參數。 分區查詢只能使用表中指示的子集。

可用於分區查詢的查詢子集和 JSON 正文參數
引數 說明 選用 類型 預設值 支援的值 分區查詢
conflicts 指定是否在傳回文件的 _conflicts 屬性中包含衝突修訂版本清單。 如果 include_docs 未設定為 true 忽略。 是 布林 否 是
descending 按 descending by key 順序返回檔案。 是 布林 否 是
end_key 當達到指定的鍵時停止返回記錄。 是 字串或 JSON 數組 是
end_key_docid 當達到指定的文檔ID時停止傳回記錄。 是 字串 是
group 指定是否按鍵將縮減結果分組。 僅當視圖中定義了reduce 函數時才有效。 如果視圖以 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 使用,當選定的複本並非所有可用複本中最快的那個時,此設定雖可能提升一致性,但代價是延遲增加且吞吐量降低。

注意 :一般而言,不建議將此參數設定為 true ,且在使用 update=true`` 時更不應如此設定。

是 布林 否 否
stale

注意:stale 已棄用。 請改用 stable 和 update。

指定是否使用過期檢視的結果,同時不觸發對包含該檢視之設計文件內所有檢視的重建。

  • ok 等同於 stable=true&update=false。
  • update_after 等同於 stable=true&update=lazy。
是 字串 否 否
start_key 傳回以指定鍵開頭的記錄。 是 字串或 JSON 數組 是
start_key_docid 傳回以指定文件 ID 開頭的記錄。 是 字串 是
update

指定在回應使用者之前是否必須更新相關視圖。

  • true - 視圖更新後傳回結果。
  • false - 傳回結果而不更新視圖。
  • lazy - 返回視圖結果而不等待更新,而是在請求後立即更新它們。
是 字串 是 是

使用 include_docs=true 可能會對 效能產生影響。

請參閱使用 HTTP 的範例,應用使用者建立的檢視,從資料庫的一個分割區中擷取包含完整文件內容的前 10 個文件清單。

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 個文件的列表,其中包括它們的完整內容。

客戶端庫使用 POST 方法而不是 GET 因為它們具有相同的行為。

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 個文件的清單的範例。

客戶端庫使用 POST 方法而不是 GET 因為它們具有相同的行為。

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 欄位以外的條件尋找文件。 例如,您可以按欄位或欄位組合進行選擇,或按使用文件內容計算的值進行選擇。 建立設計文件後就會填入索引。 在大型資料庫上,此過程可能需要一段時間。

如果發生以下事件之一,索引內容將自動增量更新:

  • 資料庫中新增了一份文件。
  • 現有文件將從資料庫中刪除。
  • 資料庫中的現有文件已更新。

當視圖定義變更或同一設計文件中的另一個視圖定義變更時,視圖索引將完全重建。 重建可確保視圖定義的變更反映在視圖索引中。 為了確保重建發生,每當更新設計文件時都會建立視圖定義的「指紋」。 如果指紋發生變化,則重建視圖索引。

當您變更設計文件中定義的所有視圖中的任何一個視圖時,都會發生視圖索引重建。 例如,如果您有一個包含三個視圖的設計文檔,並且您更新了該設計文檔,則該設計文檔中的所有三個視圖索引都會重建。 如果您想更改更大資料庫的設計文檔,請查看 設計文檔管理指南。

如果最近更新了資料庫,則存取視圖時結果可能會延遲。 延遲受到資料庫變更數量以及視圖索引是否因資料庫內容被修改而不是最新的影響。

消除這些延遲是不可能的。 對於新建立的資料庫,您可以在插入或更新文件之前在資料庫的設計文件中建立視圖定義,從而減少延遲。 在設計文件中建立視圖定義會導致插入文件時對索引進行增量更新。

如果回應速度比擁有最新資料更重要,則另一種方法是允許使用者存取舊版本的視圖索引。 若要允許存取舊版的檢視索引,請在進行檢視查詢時使用 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 強制資料庫僅使用索引的一個副本。

使用 stable=true 可能會導致高延遲,因為它僅查詢索引副本之一,即使其他副本回應速度更快。

組合參數

如果您指定 stable=false 和 update=false,您會發現結果之間存在更大的不一致,即使對於相同的查詢並且沒有進行資料庫變更也是如此。 我們建議不要使用這種組合,除非您確定您的系統可以容忍這種行為。

對傳回的行進行排序

視圖查詢傳回的資料採用數組的形式。 數組中的每個元素均使用標準 UTF-8排序進行排序。 排序應用於視圖函數中定義的鍵。

輸出的基本順序如下表所示:

返回行的順序
值 訂購
null 第一個
false
true
數字
文字(小寫)
文字(大寫)
數組(根據每個元素的值,使用此表中給出的順序)
物件(根據鍵的值,按鍵順序使用此表中給出的順序) 最後一個

您可以透過設定 descending 查詢值 true 來反轉傳回的檢視資訊的順序。

當您發出指定 keys 參數的視圖請求時,結果將以與提供的 keys 數組相同的順序傳回。

請參閱使用 HTTP 以相反排序順序請求記錄的範例:

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

請參閱以反向排序順序請求記錄的範例。

客戶端庫使用 POST 方法而不是 GET 因為它們具有類似的行為。

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 查詢參數套用篩選。 如果排序和篩選計劃組合起來沒有意義,則可能沒有行與您的鍵範圍相符。

請參閱使用 HTTP 進行全域查詢的範例,該查詢包含 start_key 以及 end_key 查詢參數:

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

請參閱包含 start_key 和 end_key 查詢參數的全域查詢範例。

客戶端庫使用 POST 方法而不是 GET 因為它們具有相同的行為。

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 文件的 身份驗證部分 的範例。

舉例來說,假設您有一個資料庫,當您使用 start_key 時,會傳回一個結果,其格式為 alpha 若將 end_key 改為 beta,您將會收到 400 (請求錯誤)的錯誤訊息,且參數順序會被顛倒。 原因是在套用關鍵篩選器之前視圖中的項目已反轉。

請參閱該範例,該範例透過 HTTP 來說明為何將 start_key 與 end_key 可能會回傳查詢解析錯誤:

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

請參閱說明為什麼顛倒 start_key 和 end_key 的順序可能會導致 400 錯誤的範例。

客戶端庫使用 POST 方法而不是 GET 因為它們具有相同的行為。

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 文件的 身份驗證部分 的範例。

end_key of beta 出現在 start_key of alpha 之前,導致查詢解析錯誤。

解決方案不僅要反轉排序順序,還要反轉 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

請參閱範例以將正確的篩選和排序套用至全域查詢。

客戶端庫使用 POST 方法而不是 GET 因為它們具有相同的行為。

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

請參閱傳回所有使用者的全域查詢範例(其中視圖匹配的鍵是 amelie.smith@aol.com 或 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"
      ]
    }
  ]
}

分頁

針對檢視使用 基於關鍵字的分頁方式。 有關具體細節和範例,請參閱 API 文件主題:檢 視查詢的分頁。

多重文件抓取

以下部分介紹了對資料庫中許多文件的 POST 請求。

對於客戶端應用程序,此技術比使用多個 GET 請求更有效。

但是,與單獨存取視圖相比,include_docs=true 可能需要額外的處理時間。

原因是,透過在視圖查詢中使用 include_docs=true,必須檢索所有結果文件才能建立客戶端應用程式的回應。 實際上,運行了一系列文件 GET 請求,每個請求都與其他應用程式請求競爭資源。

減輕這種影響的一種方法是直接從視圖索引檔案檢索結果。 省略 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"
      }
    }
  ]
}