얼마 전에 Couchbase에서 문서의 일부 또는 파편으로 작업하는 방법에 대한 글을 썼습니다.
Node.js SDK 사용. 함께 작업할 수 있다는 것은
를 사용하여 문서의 일부를
카우치베이스 서버 4.5 이상 및 하위 문서 API를 지원합니다.
NoSQL 문서로 작업할 때 모든 임베디드 JSON 데이터로 인해 매우 큰 문서가 있을 수 있기 때문에 이는 큰 문제입니다. 아마도
대용량 문서를 요청하는 것은 느리고, 현대 웹 시대에는 모든 것이 빨라야 한다는 것을 알고 계실 겁니다. 대신 다음과 같은 경우에만 요청하는 것이 더 효율적입니다.
모든 것을 한꺼번에 처리하지 않고 필요한 부분만 작업하세요.
이번에는 Node.js에서 보았던 것과 동일한 NoSQL 문서 조작을 이번에는 Go 프로그래밍 언어를 사용해 살펴보겠습니다. 해봅시다.
이 예제에 대한 데이터 스토리를 생각해 보겠습니다. 이전 예제와 동일한 데이터 스토리가 되겠지만, 다음과 같은 JSON 문서가 있다고 가정해 보겠습니다:
|
1 2 3 4 5 6 7 8 9 |
{ firstName: "Nic", lastName: "Raboy", socialNetworking: { twitter: "nraboy" } } |
위의 데이터는 기본 사용자 프로필 저장소 소셜 미디어 정보로. 모든 조작은 소셜 미디어 정보를 중심으로 이루어집니다.
를 둘러싸고 있는 상위 데이터입니다.
이 가이드에서는 간단하게 설명하기 위해 새 프로젝트로 작업하겠습니다. 이 시점에서는 Couchbase Server 4.5 이상과
컴퓨터에 GoLang이 설치 및 구성되었습니다. 아직 Couchbase용 GoLang SDK를 다운로드하지 않은 경우 명령에서 다음을 실행하세요.
프롬프트 또는 터미널:
|
1 2 3 |
go get github.com/couchbase/gocb |
이 예제의 전체 프로젝트는 하나의 파일에 저장됩니다. 이 파일을 다음과 같이 참조하겠습니다. main.go 그리고 모든
Go 프로그래밍 언어의 요구 사항을 충족하기만 하면 원하는 Go 프로젝트 디렉토리를 만들 수 있습니다.
먼저 시작하려면 다음과 같이 메인 함수입니다:
|
1 2 3 4 5 6 7 8 9 |
func main() { fmt.Println("Starting the app...") cluster, _ := gocb.Connect("couchbase://localhost") bucket, _ = cluster.OpenBucket("default", "") person := Person{FirstName: "Nic", LastName: "Raboy", SocialNetworking: &SocialNetworking{Twitter: "nraboy"}} createDocument("nraboy", &person) } |
위에서 몇 가지 주의해야 할 사항이 있습니다. 먼저 로컬로 실행 중인 Couchbase 클러스터에 대한 연결을 설정하고 있습니다. 연결에
설립되어 기본값 버킷을 추가합니다. 버킷에 값을 할당하는 것은 버킷 정의하지 않습니다. 이
를 사용하는 이유는 이 변수를 전역적으로 사용할 예정이므로 메인 함수를 호출합니다. 버킷이 열리면 다음을 수행합니다.
초기 데이터 구조를 생성합니다. 이 데이터 구조 사람 는 아래에 정의되어 있습니다:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
type Person struct { FirstName string `json:"firstname,omitempty"` LastName string `json:"lastname,omitempty"` SocialNetworking *SocialNetworking `json:"socialNetworking,omitempty"` } type SocialNetworking struct { Twitter string `json:"twitter,omitempty"` Website string `json:"website,omitempty"` } |
그리고 사람 구조체는 기본 사용자 정보를 갖고 다른 구조체를 참조합니다. 소셜 네트워킹. 모두
구조에는 비어 있는 경우 인쇄에서 제외할 JSON 속성 이름으로 태그가 지정됩니다.
다시 돌아가서 메인 함수를 사용하세요. 새 사람 개체가 웹사이트에 누락된 것을 확인할 수 있습니다. 이 기능은 나중에 추가할 예정입니다. 첫 번째
함수에서 호출하는 메인 함수가 호출됩니다. createDocument 를 호출하면 데이터베이스에 객체를 추가합니다. 이 함수
는 다음과 같이 정의됩니다:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
func createDocument(documentId string, person *Person) { fmt.Println("Upserting a full document...") _, error := bucket.Upsert(documentId, person, 0) if error != nil { fmt.Println(error.Error()) return } getDocument(documentId) getSubDocument(documentId) } |
위의 함수에서는 아직 문서 조각으로 작업하고 있지 않습니다. 먼저 새로운 데이터로 예제를 시작해야 합니다. 우리는
초기 문서에 오류가 없는 경우 호출할 것입니다. getDocument 를 사용하여 생성되었는지 확인한 다음
getSubDocument 를 사용하여 문서의 특정 부분을 가져올 수 있습니다. 문서에서 getDocument 함수는 이 애플리케이션에서 두 번 사용되며
다음과 같이 표시됩니다:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
func getDocument(documentId string) { fmt.Println("Getting the full document by id...") var person Person _, error := bucket.Get(documentId, &person) if error != nil { fmt.Println(error.Error()) return } jsonPerson, _ := json.Marshal(&person) fmt.Println(string(jsonPerson)) } |
위의 예에서 getDocument 함수를 사용하여 ID를 기준으로 전체 문서를 가져와 JSON으로 마샬링한 다음 인쇄하고 있습니다. 이
를 통해 getSubDocument 함수는 아래와 같습니다:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
func getSubDocument(documentId string) { fmt.Println("Getting part of a document by id...") fragment, error := bucket.LookupIn(documentId).Get("socialNetworking").Execute() if error != nil { fmt.Println(error.Error()) return } var socialNetworking SocialNetworking fragment.Content("socialNetworking", &socialNetworking) jsonSocialNetworking, _ := json.Marshal(&socialNetworking) fmt.Println(string(jsonSocialNetworking)) upsertSubDocument(documentId, "thepolyglotdeveloper.com") } |
위의 예에서 getSubDocument 함수를 사용하여 문서 내에서 특정 속성에 대한 조회를 수행합니다. 여기에서 작업을 시작합니다.
하위 문서 API를 사용합니다. 우리가 수행하는 조회는 소셜네트워킹 속성을 사용합니다. JSON을 참조하는 것이지
의 구조체 이름. 조각이 있으면 이를 JSON으로 마샬링한 다음 인쇄할 수 있습니다. 결과는 다음과 같아야 합니다:
|
1 2 3 4 5 |
{ "twitter": "nraboy" } |
마지막에 getSubDocument 함수를 호출하여 곧 생성될 업서트서브문서 함수를 호출합니다. 여기에서
를 사용하면 전체 문서를 먼저 가져오지 않고 문서의 일부를 수정할 수 있습니다. 이 기능은 다음과 같이 볼 수 있습니다:
|
1 2 3 4 5 6 7 8 9 10 11 |
func upsertSubDocument(documentId string, website string) { fmt.Println("Upserting part of a document...") _, error := bucket.MutateIn(documentId, 0, 0).Upsert("socialNetworking.website", website, true).Execute() if error != nil { fmt.Println(error.Error()) return } getDocument(documentId) } |
위의 함수에서는 먼저 문서 ID를 기준으로 조작할 문서를 지정합니다. 그런 다음 업서트를 수행한다고 가정합니다.
문서의 특정 경로 또는 속성을 변경합니다. 이 예제에서는 문서의 특정 경로에 웹사이트 속성에서 찾은
소셜네트워킹 부모. 이 모든 과정은 실제로 문서를 받지 않고 진행됩니다.
작업이 끝나면 전체 문서 조회를 다시 수행하여 문서가 전체적으로 어떻게 보이는지 확인합니다. 이를 원근감 있게 표현해야 하는 경우
이 프로젝트의 전체 코드는 아래에서 확인할 수 있습니다:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
package main import ( "encoding/json" "fmt" "github.com/couchbase/gocb" ) var bucket *gocb.Bucket type Person struct { FirstName string `json:"firstname,omitempty"` LastName string `json:"lastname,omitempty"` SocialNetworking *SocialNetworking `json:"socialNetworking,omitempty"` } type SocialNetworking struct { Twitter string `json:"twitter,omitempty"` Website string `json:"website,omitempty"` } func getDocument(documentId string) { fmt.Println("Getting the full document by id...") var person Person _, error := bucket.Get(documentId, &person) if error != nil { fmt.Println(error.Error()) return } jsonPerson, _ := json.Marshal(&person) fmt.Println(string(jsonPerson)) } func createDocument(documentId string, person *Person) { fmt.Println("Upserting a full document...") _, error := bucket.Upsert(documentId, person, 0) if error != nil { fmt.Println(error.Error()) return } getDocument(documentId) getSubDocument(documentId) } func getSubDocument(documentId string) { fmt.Println("Getting part of a document by id...") fragment, error := bucket.LookupIn(documentId).Get("socialNetworking").Execute() if error != nil { fmt.Println(error.Error()) return } var socialNetworking SocialNetworking fragment.Content("socialNetworking", &socialNetworking) jsonSocialNetworking, _ := json.Marshal(&socialNetworking) fmt.Println(string(jsonSocialNetworking)) upsertSubDocument(documentId, "thepolyglotdeveloper.com") } func upsertSubDocument(documentId string, website string) { fmt.Println("Upserting part of a document...") _, error := bucket.MutateIn(documentId, 0, 0).Upsert("socialNetworking.website", website, true).Execute() if error != nil { fmt.Println(error.Error()) return } getDocument(documentId) } func main() { fmt.Println("Starting the app...") cluster, _ := gocb.Connect("couchbase://localhost") bucket, _ = cluster.OpenBucket("default", "") person := Person{FirstName: "Nic", LastName: "Raboy", SocialNetworking: &SocialNetworking{Twitter: "nraboy"}} createDocument("nraboy", &person) } |
이 프로젝트를 테스트해보고 하위 문서 API가 얼마나 훌륭한지 확인해 보세요.
결론
방금 Couchbase Go SDK를 사용하여 GoLang 애플리케이션에서 Couchbase Server 하위 문서 API를 사용하는 방법을 살펴보았습니다. 더 이상 다음 사항에 대해 걱정할 필요가 없습니다.
잠재적으로 큰 용량의 NoSQL 문서를 전달하여 애플리케이션 응답 시간을 망칠 수 있습니다. 문서 용량이 크거나 다음과 같은 경우
이 API를 사용할 수 있습니다.
자세한 내용은 카우치베이스에서 확인하세요. 개발자 포털.