Hyper Ledger Query 기반 Ledger 조회

까망새부리·2023년 11월 16일
0

Hyperledger fabric은 CouchDB에서 사용하는 Query문을 통해 데이터를 조회하는 것이 가능합니다.

CouchDB Selector syntax

selector 문법의 경우 기본적으로 다음과 같은 형태를 가진다. MongoDB의 문법과 유사한 점이 있지만 특정한 기능의 경우 다른 문법을 가지는 경우가 있습니다.

{
    "selector": {
        "year": {"$gt": 2010}
    },
    "fields": ["_id", "_rev", "year", "title"],
    "sort": [{"year": "asc"}],
    "limit": 2,
    "skip": 0,
    "execution_stats": true
}

Selector 기본 문법

field 한 개 기반 조회

기본적인 Selector 문법의 경우, 하나 이상의 조회하고자 하는 필드의 정보가 필요합니다.
특정한 필드의 값을 조회하는 경우, 다음과 같은 형태의 json 데이터로 조회하는 것이 가능합니다.

{
	"director": "Lars von Trier"
}

위의 예시의 경우, diredtor 필드의 값이 Lars von Trier 인 경우를 찾아서 조회하는 문법입니다.

조금 더 복잡한 selector 표현의 경우, 연산자($regex, $eq, $gt, $gte, $lt, $lte 등)의 조합으로서 다음과 같은 표현이 가능합니다.

{
	"selector":{
		"title": "Live And Let Die"
	},
	"fields": [
		"title",
		"cast"
	]
}

field 2개 이상 조회

하나 이상의 필드를 조합한 조회를 하려면 다음과 같은 형태를 작성합니다.

{
	"name":"Paul",
	"location": "Boston"
}

위 예시의 경우, name 필드의 값이 Paul, location의 값이 Boston인 경우를 조회합니다.

Subfield 조회

조금 더 복잡한 subfiled 조회는 다음과 같은 방법으로 조회하는 것이 가능합니다.
기본적으로는 json형태로 조회하며, 점 표기법을 사용하여 조회하는 것도 가능합니다.

{
	"imdb":{
		"rating" : 8
	}
}
or
{
	"imdb.rating" : 8
}

Operators

연산자들은 달러 표시 $를 name 필드 앞 단에 붙여서 구분하여 사용할 수 있습니다.
연산자는 2 종류의 연산자 타입을 가지고 있습니다.

  • Combination operators
  • Condition operators

일반적으로 Combination 연산자의 경우는 최상급의 선택 단계에서 적용이 되며,
Condition 연산자의 경우에는 하나 이상의 selector로 조합하여 사용합니다.

Implicit Operators

2 종류의 implicit operator가 있습니다.

  • Equality
  • And

두 개의 연산자는 선언하지 않더라도 선언이 된 것으로 간주가 됩니다.
예를 들어

{
	"director": "Lars von Trier"
}

{
	"director": {
		"$eq": "Lars von Trier"
	}
}

위의 2개의 json 데이터는 결과적으로 같은 결과를 가져옵니다.

Explicit Operators

EqualityAnd 연산을 제외한 모든 연산자는 명확하게 명시해야 합니다.

Combination Operators

Combination Operators는 selectors를 조합하는데 사용합니다.
대부분의 프로그래밍 언어가 제공하는 boolean 연산자처럼 $all, $elemMatch, $allMatch 등의 연산자는 Json 배열 또는 Json 데이터를 비교합니다.

Combination Operator는 하나의 인자를 받아서 사용합니다. 인자는 하나 혹은 배열 형태의 데이터를 사용합니다.

Combination Operators List
OperatorArgumentPurpose
$andArray배열의 모든 Selector가 일치하는 경우를 조회
$orArray배열에 있는 Selector 중 하나라도 일치한다면 조회
$notSelectorSelector와 일치하지 않는 데이터들을 조회
$norArray배열의 Selector가 일치하지 않으면 조회
$allArray배열의 모든 요소를 포함하는 경우 조회
$elemMatchSelectorMatches and returns all documents that contain an array field with at least one element that matches all the specified query criteria.
$allMatchSelectorMatches and returns all documents that contain an array field with all its elements matching all the specified query criteria.
$keyMapMatchSelectorMatches and returns all documents that contain a map that contains at least one key that matches all the specified query criteria.

$and 연산자는 2개의 필드를 사용한다.

{
  "selector": {
    "$and": [
      {
        "title": "Total Recall"
      },
      {
        "year": {
          "$in": [1984, 1991]
        }
      }
    ]
  },
  "fields": [
      "year",
      "title",
      "cast"
  ]
}

Condition Operators

Condition Operators는 저장되어 있는 특정한 데이터의 값을 평가하는데 사용이 됩니다.
예를 들어서, $eq 연산자의 경우 저장된 데이터가 같은 값을 가지고 있는지 확인하는 기능을 합니다.

Condition Operators는 반드시 문서에 조회하고자 하는 Selector가 존재해야 합니다.
$ne 연산자의 경우 데이터가 반드시 존재하고, 데이터 값이 같지 않음을 의미합니다.

Condition Operators List
Operator typeOperatorArgumentPurpose
(In)equality$ltAny JSONThe field is less than the argument.
$lteAny JSONThe field is less than or equal to the argument.
$eqAny JSONThe field is equal to the argument
$neAny JSONThe field is not equal to the argument.
$gteAny JSONThe field is greater than or equal to the argument.
$gtAny JSONThe field is greater than the to the argument.
Object$existsBooleanCheck whether the field exists or not, regardless of its value.
$typeStringCheck the document field’s type. Valid values are "null""boolean""number""string""array", and "object".
Array$inArray of JSON valuesThe document field must exist in the list provided.
$ninArray of JSON valuesThe document field not must exist in the list provided.
$sizeIntegerSpecial condition to match the length of an array field in a document. Non-array fields cannot match this condition.
Miscellaneous$mod[Divisor, Remainder]Divisor is a non-zero integer, Remainder is any integer. Non-integer values result in a 404. Matches documents where field % Divisor == Remainder is true, and only when the document field is an integer.
$regexStringA regular expression pattern to match against the document field. Only matches when the field is a string value and matches the supplied regular expression. The matching algorithms are based on the Perl Compatible Regular Expression (PCRE) library. For more information about what is implemented, see the see the Erlang Regular Expression.
$beginsWithStringMatches where the document field begins with the specified prefix (case-sensitive). If the document field contains a non-string value, the document is not matched.

Sort Syntax

sort 필드는 필드의 이름, 정렬 방향이 기본적인 배열 형태로 표현이 됩니다.
첫 번째로 오는 필드의 이름과 방향이 가장 먼저 정렬이 되는 기준이 되며, 뒤에 오는 순서대로 정렬 규칙이 적용이 됩니다.

asc 는 오름차순, desc는 내림차순 정렬을 하고자 할 때 사용합니다.
특정한 방향을 입력하지 않는 경우 기본적으로 오름차순으로 정렬이 됩니다..

[{"fieldName1": "desc"}, {"fieldName2": "desc" }]

정렬 기능을 사용하려면 다음과 같은 정보를 확인해야만 합니다.

  • 최소한 하나의 정렬 필드를 selector에 포함 되어야 한다.
  • 모든 정렬 필드가 동일한 index 값이 적용이 되어 있어야 한다.
  • 정렬 배열의 각 객체에는 single key가 하나 존재해야 한다.

만약 single key를 가지고 있지 않는 경우, 정렬의 결과는 구현의 방향에 따라서 달라질 수 있습니다.
간단한 정렬 쿼리문의 예시는 다음과 같습니다.

{
    "selector": {"Actor_name": "Robert De Niro"},
    "sort": [{"Actor_name": "asc"}, {"Movie_runtime": "asc"}]
}

Filtering Fields

필터를 통해서 가지고 오는 정보의 필드를 정확하게 지정하는 것이 가능합니다.
이러한 과정을 통해서, 다음과 같은 2가지 이점을 가져올 수 있습니다.

  • Application에서 요구하는 특정한 데이터를 제한적으로 가져올 수 있다.
  • 응답 데이터의 사이즈를 줄일 수 있다.

특정한 필드를 포함한 응답 데이터의 경우, 자동적으로 _id 같은 metadata 필드 정보를 자동으로 포함하지 않고 반환합니다.

예시 형태는 다음과 같습니다.

{
    "selector": { "Actor_name": "Robert De Niro" },
    "fields": ["Actor_name", "Movie_year", "_id", "_rev"]
}

Pagination

Mango query는 bookmark 필드를 통해서 Pagination 기능을 지원합니다. 모든 _fine 응답은 bookmark 값을 포함합니다.
다음 query의 결과를 가져오기 위해서는 selector값을 동일하게 유지한 다음, 다음의 bookmark 값을 추가하여 가져올 수 있습니다.

Pagination의 결과가 마지막에 도달했는지 확인하는 법은 size_request - result의 결과가 < limit 값을 비교하여 더 이상 없는 것을 확인할 수 있습니다.

Execution Statistics

특정한 요청을 통해서 기본적인 통계 정보를 제공하고 있습니다. _explain endpoint 값을 포함하여 유용한 데이터 값을 제공 받을 수 있습니다.

필드 값설명
total_keys_examined검사한 index의 데이터 수를 의미합니다.
total_docs_examinedNumber of documents fetched from the database / index, equivalent to using include_docs=true in a view. These may then be filtered in-memory to further narrow down the result set based on the selector.
total_quorum_docs_examinedNumber of documents fetched from the database using an out-of-band document fetch. This is only non-zero when read quorum > 1 is specified in the query parameters.
results_returned쿼리에서 나오는 결과 값을 의미합니다.
execution_time_ms총 실행하는 시간을 의미합니다.

Reference

profile
배움을 찾는 사람이 되자!

0개의 댓글