我正在尝试使用官方 Java SDK 搜索 IBM cloudant DB 以检索与提供的字段值匹配的文档。 SDK 文档没有提到我们如何在没有 docId 的情况下进行查询,而是使用其他字段,就像我们可以从 Web 仪表板中执行的操作一样。如果有人使用 java 做过类似的事情,请分享代码片段。
{ "_id": "xxxxxx", "_rev": "xxxxxxxxx", "key": "yyyyyyyyy", "doc": { "empName": "Bob", "empNo": "123" } }
例如,我想使用 Java SDK 获取所有包含“empName”:“Bob”的文档。
期望匹配特定搜索条件的文档列表。
在字段empName
上创建索引:
IndexField field = new IndexField.Builder()
.add("empName", "asc")
.build();
IndexDefinition indexDefinition = new IndexDefinition.Builder()
.addFields(field)
.build();
PostIndexOptions indexOptions = new PostIndexOptions.Builder()
.db("empDb")
.ddoc("json-indexes")
.index(indexDefinition)
.name("getEmpByName")
.type("json")
.build();
IndexResult response =
service.postIndex(indexOptions).execute()
.getResult();
// Check OK etc
然后使用选择器查询索引:
Map<String, Object> selector = Collections.singletonMap(
"empName",
Collections.singletonMap("$eq", "Bob"));
PostFindOptions findOptions = new PostFindOptions.Builder()
.db("empDb")
.selector(selector)
.build();
List<Document> docs =
service.postFind(findOptions).execute()
.getResult().getDocs();
这个带有 json 类型索引的查询 API 由 map-reduce 视图 支持。 文本索引也可用于支持查询。可以直接在 设计文档 中创建索引并与 View 或 Search API 交互,而不是使用本示例中所示的
_index
/_find
风格。