Couchbase:如何维护没有重复元素的数组?

ram*_*amu 5 couchbase couchbase-java-api

我们有一个包含客户数据的 Couchbase 商店。

  • 每个客户在这个存储桶中只有一个文档。
  • 每日交易将导致更新此客户数据。

示例文档。让我们专注于purchase_product_ids数组。

{
  "customer_id" : 1000
  "purchased_product_ids" : [1, 2, 3, 4, 5 ] 
      # in reality this is a big array - hundreds of elements
  ... 
  ... many other elements ...
  ...
} 

Existing purchased_product_ids : 
    [1, 2, 3, 4, 5]

products purchased today : 
    [1, 2, 3, 6]  // 6 is a new entry, others existing already

Expected result after the update: 
    [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

我使用Subdocument API来避免服务器和客户端之间的大量数据传输。

选项1“arrayAppend”:

customerBucket.mutateIn(customerKey)
    .arrayAppend("purchased_product_ids", JsonObject for [1,2,3,6] )
    .execute();

It results in duplicate elements. 
"purchased_product_ids" : [1, 2, 3, 4, 5, 1, 2, 3, 6]
Run Code Online (Sandbox Code Playgroud)

选项2“arrayAddUnique”:

customerBucket.mutateIn(customerKey)
    .arrayAddUnqiue("purchased_product_ids", 1 )
    .arrayAddUnqiue("purchased_product_ids", 2 )
    .arrayAddUnqiue("purchased_product_ids", 3 )
    .arrayAddUnqiue("purchased_product_ids", 6 )
    .execute();

It throws exception for most of the times, 
because those elements already existing.
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来进行此更新?

Joh*_*son 4

您可以使用 N1QL、ARRAY_APPEND() 和 ARRAY_DISTINCT() 函数。

UPDATE customer USE KEYS "foo" 
SET purchased_product_ids = ARRAY_DISTINCT(ARRAY_APPEND(purchased_product_ids, 9))
Run Code Online (Sandbox Code Playgroud)

据推测,这将是一个准备好的语句,并且键本身和新值将作为参数提供。

另外,如果您想一次向数组添加多个元素,ARRAY_CONCAT() 将是更好的选择。更多这里:

https://docs.couchbase.com/server/6.0/n1ql/n1ql-language-reference/arrayfun.html