在Spring-data-Couchbase中直接将文档另存为id的值

时间:2019-04-16 09:26:40

标签: couchbase spring-data-couchbase

我想将JSON对象另存为Couchbase中的文档。应该从此JSON对象中检索此文档的ID,并且值应该是此JSON对象本身。由于此JSON太复杂,因此我没有将其直接映射到任何POJO类,但是我创建了一个简单的POJO,它具有两个字段,如下所示

@Document
public class SimplePojo{

    @Id
    private String id;

    @Field()
    private String complexJsonString;//the JSON string is stored in this variable
}

我还有一个SimplePojoRepository,如下所示

@Component
public interface SimplePojoRepository extends CouchbaseRepository<SimplePojo, String>{
}

现在,我将在调用save方法之前手动设置id和complexJsonString:-

 SimplePojo myObj= new SimplePojo();
 myObj.setId(myKey);
 myObj.setComplexJsonString(jsonString);
 simplePojoRepository.save(myObj); 

这很好,但是它以以下格式保存了文档

myKey: {
  complexJsonString : {//the original json Object here}
}

但是我不想这样,我想这样保存它:-

myKey : {//the original json Object here}

因此,为了明确起见,我不想将JSON对象保存为complexJsonString的值,而是直接保存为myKey的值。有人可以指导我如何实现这一目标吗?

1 个答案:

答案 0 :(得分:2)

如果要将complexJsonString作为嵌套实体存储在主对象中,则必须在Pojo中对其进行转换:

myObj.setSomeEntity(new SomeEntity())

您可以使用杰克逊的ObjectMapper轻松地将JSON编码的字符串转换为对象:

ObjectMapper mapper = new ObjectMapper();
mapper.readValue( jsonString, SomeEntity.class);

但是,如果您无法控制此json的结构,则需要使用标准的Java SDK而不是Spring Data One:

JsonObject obj = JsonObject.create().put(this.documentTypeName, this.documentValue)
                    .put("attrNam1", "attrValue1")
                    .put("attrNam2", "attrValue2")

JsonDocument doc = JsonDocument.create(session.getId(), maxExpirationTime, obj);
bucket.upsert(doc)

在上述情况下,您将需要使用某个lib(例如gson / jackson)解析您的JSON编码的字符串,然后将其转换为Couchbase JsonDocument。

最后,您还可以保留您的代码,并在需要访问此json字符串的某些属性时使用N1QL函数DECODE_JSON()

例如:

SELECT
    i.itemName as itemName,
    SUM(i.quantity) AS totalQuantity
FROM sessionstore s
UNNEST DECODE_JSON(s.sessionCart).shoppingCart.items i
WHERE s.sessionCart IS NOT MISSING
GROUP BY i.itemName
ORDER BY SUM(i.quantity) DESC
LIMIT 10

相关问题