Sorting Results

DQL allows you to define the sort order of your results in various ways, including sorting on a particular response field, reverse-sorting on a field, and sorting in a random order.

Sort By

The sortBy operator is used to specify that results should be sorted by a particular field. Note that results are sorted in ascending order by default.

For example: This query will match all organizations located in the city of San Francisco, and return them in ascending order by name:

type:Organization isPublic:true location.city.name:"San Francisco" sortBy:name

📘

Due to legacy reasons, sorting on the Article.date field works differently. When using sortBy:dateor sortBy:date.timestamp, articles return the latest articles first. Similarly, when using revSortBy:dateor revSortBy:date.timestamp, articles return the oldest articles first.

Nested Sort

You can also specify a filter on the sort clause. This is useful when sorting on nested fields.

For example: To search for engineers currently employed at Uber Technologies and sort by their start date, specify:

type:Person employments.{employer.name:"Uber Technologies" categories.name:"Engineering" isCurrent:true} sortBy:employments.{from employer.name:"Uber Technologies" isCurrent:true}

Note how this is different from

type:Person
  employments.{employer.name:"Uber Technologies" categories.name:"Engineering" isCurrent:true}
  sortBy:employments.from

which sorts by all start dates in the nested employment field.

Reverse Sort By

The revSortBy operator is used to specify that results should be sorted according to a particular field, but in descending order.

For example: To search for all articles published by New York Times and return them in order by date published, from oldest to most recent, specify:

type:Article pageUrl:"nytimes.com" revSortBy:date

Random Sorting

We can use the parameter sortBy:random to have the results returned in a totally random order.

For example: To retrieve all organizations who have ever had an address in the United States, and return them in a random order, you can specify:

type:Organization locations.country.name:"United States" sortBy:random

Random Sorting with Seed

We can use the parameter sortBy:randomSeed with some integer value to have the results returned in a predictable random order.

For Example: This query will match all organizations with a presence in the United States, and return them in a predictably and reproducible random order:

type:Organization locations.country.name:"United States" sortBy:randomSeed:501

The key thing to note here is that this query will always produce the exact same sort order, and as long as the set of results has not changed (as a result of a KG update) the response will always be identical.