Back to top

ReQL command: slice

Command syntax

selection.slice(startOffset[, endOffset]) → selection

stream.slice(startOffset[, endOffset]) → stream

array.slice(startOffset[, endOffset]) → array

binary.slice(startOffset[, endOffset]) → binary

string.slice(startOffset[, endOffset]) → string

Description

Return the elements of a sequence within the specified range.

slice returns the range between startOffset and endOffset. If only startOffset is specified, slice returns the range from that index to the end of the sequence. Use the optArgs left_bound or right_bound as open or closed to indicate whether to include that endpoint of the range by default: closed returns that endpoint, while open does not. By default, left_bound is closed and right_bound is open, so the range (10,13) will return the tenth, eleventh and twelfth elements in the sequence.

If endOffset is past the end of the sequence, all elements from startOffset to the end of the sequence will be returned. If startOffset is past the end of the sequence or endOffset is less than startOffset, a zero-element sequence will be returned.

Negative startOffset and endOffset values are allowed with arrays; in that case, the returned range counts back from the array’s end. That is, the range (-2) returns the last two elements, and the range of (2,-1) returns the second element through the next-to-last element of the range. An error will be raised on a negative startOffset or endOffset with non-arrays. (An endOffset of −1 is allowed with a stream if rightBound is closed; this behaves as if no endOffset was specified.)

If slice is used with a binary object, the indexes refer to byte positions within the object. That is, the range (10,20) will refer to the 10th byte through the 19th byte.

With a string, slice behaves similarly, with the indexes referring to Unicode codepoints. String indexes start at 0. (Note that combining codepoints are counted separately.)

Example: Return the fourth, fifth and sixth youngest players. (The youngest player is at index 0, so those are elements 3–5.)

r.table("players").orderBy().optArg("index", "age").slice(3, 6).run(conn);

Example: Return all but the top three players who have a red flag.

r.table("players").filter(r.hashMap("flag", "red")).orderBy()
 .optArg("index", r.desc("score")).slice(3).run(conn);

Example: Return holders of tickets X through Y, assuming tickets are numbered sequentially. We want to include ticket Y.

r.table("users").orderBy().optArg("index", "ticket")
 .slice(x, y).optArg("right_bound", "closed").run(conn);

Example: Return the elements of an array from the second through two from the end (that is, not including the last two).

r.expr(r.array(0, 1, 2, 3, 4, 5)).slice(2, -2).run(conn);

Result:

[2,3]

Example: Return the third through fifth characters of a string.

r.expr("rutabaga").slice(2,5).run(conn);

Result:

"tab"

Get more help

Couldn't find what you were looking for?