How can we search IBM cloudant DB to retrieve documents that match supplied field values?

26 Views Asked by At

I am trying to search IBM cloudant DB to retrieve documents that match supplied field values using official Java SDK. The SDK documentation does not mention how can we query without docId, but using other fields as we can do from the web dashboard. If anyone has done similar stuff using java please share code snippets. { "_id": "xxxxxx", "_rev": "xxxxxxxxx", "key": "yyyyyyyyy", "doc": { "empName": "Bob", "empNo": "123" } }

e.g I want to get all documents which have "empName": "Bob" using Java SDK.

Expecting a list of documents that match specific search criteria.

1

There are 1 best solutions below

0
ricellis On

Create an index on the field 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

Then query the index with a selector:

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

This query API with a json type index is backed by a map-reduce view. Text indexes are also available to back queries. It is possible to create indexes directly in design documents and interact with the View or Search APIs instead of using the _index/_find with selector style shown in this example.