ben-bdj
ben-bdj

Reputation: 11

getStateByRange - End of String indication for exact search

When using getStateByRange in Java chaincode (and presumably other languages also), a search for "asset10" through "asset11" will retrieve asset10, and anything with characters after asset10 (e.g. asset100, asset101...).

Is there any character or control sequence to prevent this, and just retrieve asset10? Unicode NULL and end of string don't appear to make any difference.

Upvotes: 1

Views: 96

Answers (1)

Oguz Tecirlioglu
Oguz Tecirlioglu

Reputation: 53

The GetStateByRange method in Hyperledger Fabric performs a lexicographical search on the keys. The search starts from the specified startKey (inclusive) and goes up to, but not including, the specified endKey (exclusive). You can also specify the empty string ("") to create an unbounded search, that returns an iterator to all assets with basic keys (not composite keys!).

In your example, GetStateByRange("asset10", "asset11") retrieves keys such as "asset10", "asset100", "asset101", and so on, because of this ordering as they fall within the range defined by the start and end keys.

Lexicographical ordering means the comparison of characters in a string based on their ASCII values. For example, in ASCII, "a" comes before "b", "A" comes before "a", and so on. Therefore, when using GetStateByRange, keys are sorted lexicographically, and the query returns all keys between the start and end keys based on this ordering.

In your example, the search compares the final 1 in "asset11" to the 7th character, which is a 0 in "asset101" and determines that it is lexicographically smaller, and therefore adds it to the return list.

If you just want to receive asset10, you can make:

  • Your startKey = "asset10"
  • Your endkey = "asset100"

Or make the last character of the endKey the smallest ASCII character that suits your needs, it could also be "asset10!" for example, as this would satisfy your search criteria.

Upvotes: 0

Related Questions