How to create views/secondary index for SerializableDocument in couchbase

347 views Asked by At

I am using scala to connect with bucket and insert data in bucket.

case class User(
firstName: String,
lastName: String,
userName: String,
email: String)

bucket.upsert(SerializableDocument.create("usr::" + user.email,user))

I am able to insert and retrieve data from bucket. Now I want to create view/secondary index on firstName field of user.

val ensureIndex = Query.simple("CREATE INDEX firstName ON `user_account`(firstName)");
 val queryResult = bucket.query(ensureIndex)

val queryResult = bucket.query(ViewQuery.from("dev_ddl_firstName", "firstName"))

But I am getting 0 as result of queryResult.totalRows().

Can anyone help me a correct way for creating view/secondary index on field in couchbase?

Thanks in advance.

2

There are 2 answers

0
Simon Baslé On

additionally to what Matt Ingenthron said, SerializableDocument in the Java SDK is storing data with a binary flag. Views can only index content of JSON document, not binary ones...

You can either use the marshaller of your choice to transform your instance to a JSON String and use the RawJsonDocument with it, or let the SDK marshall it with Jackson by doing a conversion of your document to a JsonObject (a SDK simple JSON manipulation class, but more meant for Java) and use the JsonDocument.

0
Matt Ingenthron On

You're mixing two concepts there. The index definition is for a N1QL query, though it does create a view. Typically, if you create the index through a N1QL query, you'll query with N1QL.

The query you're running is on the view created by it. My suspicion is that you need to publish it or use the full_set parameter against the development view. It may be better to stick with a N1QL query.