【发布时间】:2016-07-11 16:20:43
【问题描述】:
是否可以使用 Couchbases Java Client 2.2.2 以编程方式创建和发布二级索引?我希望能够创建和发布运行 Couchbase 4.1 的自定义二级索引。我知道这可以用 Couchbase Views 来做,但我找不到索引。
【问题讨论】:
标签: java indexing couchbase couchbase-java-api
是否可以使用 Couchbases Java Client 2.2.2 以编程方式创建和发布二级索引?我希望能够创建和发布运行 Couchbase 4.1 的自定义二级索引。我知道这可以用 Couchbase Views 来做,但我找不到索引。
【问题讨论】:
标签: java indexing couchbase couchbase-java-api
需要couchbase-java-client-2.3.1 以便以编程方式创建主要或次要索引。一些可用的方法可以在用于 upsert 视图的bucketManger 上找到。另外可以使用静态方法createIndex,它支持DSL和String语法
有几个选项可以创建二级索引。
选项#1:
Statement query = createIndex(name).on(bucket.name(), x(fieldName));
N1qlQueryResult result = bucket.query(N1qlQuery.simple(query));
选项#2:
String query = "BUILD INDEX ON `" + bucket.name() + "` (" + fieldName + ")";
N1qlQueryResult result = bucket.query(N1qlQuery.simple(query));
选项#3(实际上这里有多个选项,因为方法createN1qlIndex被重载了
bucket.bucketManager().createN1qlIndex(indexName, fields, where, true, false);
【讨论】:
主索引:
// Create a N1QL Primary Index (ignore if it exists)
bucket.bucketManager().createN1qlPrimaryIndex(true /* ignore if exists */, false /* defer flag */);
二级索引:
// Create a N1QL Index (ignore if it exists)
bucket.bucketManager().createN1qlIndex(
"my_idx_1",
true, //ignoreIfExists
false, //defer
Expression.path("field1.id"),
Expression.path("field2.id"));
或
// Create a N1QL Index (ignore if it exists)
bucket.bucketManager().createN1qlIndex(
"my_idx_2",
true, //ignoreIfExists
false, //defer
new String ("field1.id"),
new String("field2.id"));
如果您的文档是这样的,第一个二级索引 (my_idx_1) 会很有帮助:
{
"field1" : {
"id" : "value"
},
"field2" : {
"id" : "value"
}
}
如果您的文档是这样的,第二个二级索引 (my_idx_2) 会很有帮助:
{
"field1.id" : "value",
"field2.id" : "value"
}
【讨论】:
一旦你有一个 Bucket,你应该可以用任何 2.x 做到这一点
bucket.query(N1qlQuery.simple(queryString))
queryString 类似于
String queryString = "CREATE PRIMARY INDEX ON " + bucketName + " USING GSI;";
【讨论】:
截至java-client 3.x+ 有一个QueryIndexManager(通过cluster.queryIndexes() 获得),它提供了一个索引API,具有以下创建索引的特定方法:
createIndex(String bucketName, String indexName, Collection<String> fields)
createIndex(String bucketName, String indexName, Collection<String> fields, CreateQueryIndexOptions options)
createPrimaryIndex(String bucketName)
createPrimaryIndex(String bucketName, CreatePrimaryQueryIndexOptions options)
【讨论】: