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

请求要么运行

  • 来自指定 $VIEW_NAME 设计文件的指定 $DDOC 数据库 数据库中的指定 $DATABASE,其结果受限于指定的 $PARTITION_KEY data partition.
  • 指定的 $VIEW_NAME 来自指定的 $DDOC 设计文档 数据库中的指定 $DATABASE

本文档中的示例既有分区查询,也有全局查询,以说明问题。 的示例。 除非另有说明,修改路径以 嵌入或移除分区名称的路径对任何视图查询类型都有效。

查询和 JSON 正文参数

全局查询可使用所有查询和 JSON 主体参数。 分区查询只能使用 表中显示的子集。

可用于分区查询的查询和 JSON 主体参数子集
自变量 描述 可选 Type 缺省 支持的值 分区查询
conflicts 指定是否在返回文档的 _conflicts 属性中包含冲突修订列表。 如果 include_docs 未设置为 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 的记录。 布尔值 True
key 只返回与指定关键字匹配的文件。 键值是 JSON 值,必须使用 URL 编码。 JSON 数组
keys 指定只返回与指定关键字匹配的文档。 与视图函数发出的键类型相匹配的 JSON 键数组的字符串表示。 字符串或 JSON 数组
limit 将返回的文件数量限制在指定的数量内。 数值
reduce 使用 reduce 功能。 布尔值 True
skip 从一开始就跳过这个行数。 数值 0
stable 指定是否在每次请求中使用相同的索引副本。 默认值 false 联系所有副本,并从第一个最快的应答器返回结果。 将其设置为true 时,如果所选副本不是可用副本中速度最快的,那么与update=false 一起使用时,可能会以增加延迟和降低吞吐量为代价提高一致性

注意:一般情况下,不鼓励将此参数设置为 true,也不建议使用 update=true

布尔值
stale

stale 已被弃用。 用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 指定在回复用户之前是否必须更新相关视图
- true- 在视图更新后返回结果
- false- 返回结果时不更新视图。
- lazy- 返回视图结果时不等待更新,但在收到请求后立即更新。
字符串 True

使用 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

请参阅示例,应用用户创建的 small-appliances 视图,从数据库的 byApplianceProdId 分区中检索包含全部内容的前 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))

前面的围棋示例需要以下导入块:

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

前面的围棋示例需要以下导入块:

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提供了一些参数、 来改变这一行为。 我们建议不要使用 因为它们的副作用通常会超过它们的益处。

参数

The update option indicates whether you're prepared to accept view results without waiting for the view to be updated. 默认值 默认值为 true,表示在返回结果之前更新视图。 返回结果。 The lazy value means that the results are returned before the view is updated, but that the view must then be updated anyway.

虽然IBM Cloudant会努力 在后台更新索引,但无法保证 在使用 update=falseupdate=lazy.

The stable option indicates whether you would prefer to get results from a single, consistent set of shards. The false value means that all available shard replicas are queried and IBM Cloudant使用最快的 响应。 相比之下,设置 stable=true forces the database to use just one replica of the index.

使用 stable=true 会导致较高的延迟,因为它 会导致较高的延迟,因为它只查询索引的一个副本,即使其他副本的 响应更快。

组合参数

如果指定 stable=falseupdate=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))

前面的围棋示例需要以下导入块:

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_keyend_key 可用来指定查询视图时返回的值范围。 查询视图时返回的值范围。

排序方向总是先应用。 然后,使用 start_keyend_key 查询参数进行过滤。 如果排序和筛选计划在组合时没有意义,则可能没有符合关键范围的记录。

请参阅使用 HTTP 进行包含 start_keyend_key 的全局查询的示例 查询参数:

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

请参阅包含 start_keyend_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))

前面的围棋示例需要以下导入块:

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

所有 Go 示例都要求 service 对象初始化。 有关更多信息,请参阅 API 文档中的 "身份验证 "部分 的示例。

例如,如果您有一个数据库,当您使用 alphastart_key 时,返回一个结果 和 betaend_key,就会出现顺序颠倒的 400(错误请求)错误。 原因是在应用关键字过滤器之前,视图中的条目是反向的。

请参阅使用 HTTP 的示例,以说明为什么要颠倒 start_keyend_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 错误。

客户端库使用 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))

前面的围棋示例需要以下导入块:

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

所有 Go 示例都要求 service 对象初始化。 有关更多信息,请参阅 API 文档中的 "身份验证 "部分 的示例。

betaend_keyalphastart_key 之前出现,导致查询解析错误。

The solution is to reverse not just the sort order, but also the start_key and end_key parameter values.

The following example shows correct filtering and reversing the order of output, by using the descending query argument, and reversing the start_key and end_key query arguments.

请参阅使用 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))

前面的围棋示例需要以下导入块:

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

所有 Go 示例都要求 service 对象初始化。 有关更多信息,请参阅 API 文档中的 "身份验证 "部分 的示例。

使用键列表查询视图

您还可以通过提供要使用的键列表来运行查询。

Requesting information from a database in this way uses the specified $VIEW_NAME from the specified $DDOC design document. 与 GET 方法的 keys 参数一样、 方法一样,你可以使用 POST 方法来指定用于检索视图结果的键。 In all other aspects, the POST method is the same as the GET API request. 特别是 可以在查询字符串或 JSON 主体中使用任何查询参数。

请参阅返回所有用户的 HTTP 请求示例,其中视图的关键字匹配 amelie.smith@aol.combob.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))

前面的围棋示例需要以下导入块:

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 请求,每个请求都要与其他应用程序请求争夺资源。

减轻这种影响的一种方法是直接从视图索引文件中检索结果。 省略 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))

前面的围棋示例需要以下导入块:

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