TRUNCATE_SET function

The TRUNCATE_SET row function takes a set and an integer, and returns a copy of the set with no more than the specified number of elements in it.

The syntax of the TRUNCATE_SET function is:
TRUNCATE_SET(<set>, <max-size>)
where:
  • set is a set of any set data type (such as mdex:string-set or mdex:long-set). For example, set can be a multi-assign string attribute.
  • max-size is an integer that specifies the maximum size of the truncated set. If max-size is less than the number of elements in the set, the Dgraph arbitrarily chooses which elements to discard; this choice is stable across multiple executions of the query. If max-size is 0 (zero) or a negative number, the empty set is returned.
Examples of some results are as follows ({ } indicates an empty set):
TRUNCATE_SET({ }, 2) = { }
TRUNCATE_SET({ 'a', 'b' }, 2) = { 'a', 'b' }
TRUNCATE_SET({ 'a', 'b', 'c' }, 2) = { 'b', 'c' }
TRUNCATE_SET({ 1, 2 }, 20) = { 1, 2 }
TRUNCATE_SET({ 1, 2 }, -3) = { }

TRUNCATE_SET is useful when you want to ensure that final results of a set are of a reasonable and manageable size for your front-end UI.

TRUNCATE_SET example

In this example, Flavors is a multi-assign string attribute and WineID is the primary key of the records:
RETURN results AS
SELECT
   WineID AS id,
   Flavors AS fullFlavors,
   TRUNCATE_SET(fullFlavors, 1) AS truncFlavors
FROM WineState
WHERE WineID BETWEEN 15 AND 19
ORDER BY id
The result of this statement might be:
fullFlavors                           id     truncFlavors
-------------------------------------------------------------
| { Blackberry, Oaky, Strawberry }  | 15 | { Blackberry }   |
| { Currant, Licorice, Tobacco }    | 16 | { Licorice }     |
| { Cedar, Cherry, Spice }          | 17 | { Cherry }       |
| { Black Cherry, Cedar, Fruit }    | 18 | { Black Cherry } |
| { Herbal, Strawberry, Vanilla }   | 19 | { Herbal }       |
-------------------------------------------------------------

The fullFlavors set shows the full set of Flavors assignments on each of the five chosen records. The fullFlavors set is then truncated to a one-element set.