RQL (Ruhis Query Language) is a powerful library designed to simplify the process of filtering, sorting, and aggregating large amounts of data. With RQL, you can effortlessly extract valuable insights from complex datasets, making data analysis and manipulation tasks more efficient. RQL was initially developed for an internal SIEM project, so it is well suited for security-related use cases, but it can be used for any type of data.
- Simple and intuitive syntax - RQL is designed to be easy to learn and use. The syntax is similar to KQL or XQL, but with a few key differences that make it more intuitive and powerful.
- Light, type-safe and developer friendly - RQL is written in TypeScript and compiled to JavaScript. It is very lightweight and has a great documentation, making it easy to integrate into any project.
- Thoroughly tested - RQL has a comprehensive test suite with a very code coverage, ensuring that it works as expected in all scenarios.
-
Install via your preferred package manager:
npm install @ruhisfi/rqlyarn add @ruhisfi/rql
-
Import
QueryParserandQueryExecutorto your code:import { QueryParser, QueryExecutor } from "@ruhisfi/rql";
-
Parse query and execute it against a dataset:
const query = 'dataset = example_data | filter name = "John" or country = "Finland" | fields name, country, city, email, age | sort age desc | limit 10'; const parsedQuery = QueryParser.parseQuery(query); // This will validate the query and convert it into a JS object const result = QueryExecutor.executeQuery(parsedQuery, data); // This will execute the query against the dataset
The query consists of multiple statements separated by the pipe (|) character. The statements are case-sensitive, and must be written in lowercase. The query lines can be commented out with #. The statements are executed in the order they are written in the query.
The following operators are supported in RQL:
| Operator | Description |
|---|---|
| =, != | Equal, Not equal |
| >, < | Greater than, Less than |
| >=, <= | Greater than or equal, Less than or equal |
| and | Boolean AND |
| or | Boolean OR |
| contains | Returns true if the specified value is contained in string or array |
| not contains | Returns true if the specified value is not contained in string or array |
| matches, ~= | Returns true if the regex pattern matches |
| incidr | Returns true if the IP address is in the CIDR range |
| not incidr | Returns true if the IP address is not in the CIDR range |
| in | Returns true if the value is in the specified list |
| not in | Returns true if the value is not in the specified list |
alter <name> = <function>
The alter statement is used to create new or overwrite existing fields in the dataset using a value functions like addition, subtraction, letter casing, etc. The alter statement can be used multiple times in a query and the fields created by it can be used in other statements.
Supported functions can be found in the documentation: RQL Docs - Functions
dataset = products
| filter ean = "6410405082657"
| alter price = multiply(cost, 1.2)
| fields ean, name, cost
comp <function> <field> [as <returnField>] [by <groupingField>][, <function> <field> [as <returnField>], ...]
The comp statement is used to calculate statistics for results. This function will override other returned records. If used multiple times, the statistics will be merged on one row.
| Function | Description |
|---|---|
| avg | Returns the average value of the field |
| count | Returns the number of records where field is not null |
| count_distinct | Returns the number of distinct values where field is not null |
| earliest | Returns the earliest timestamp |
| first | Returns the first value |
| last | Returns the last value |
| latest | Returns the latest timestamp |
| max | Returns the maximum value |
| median | Returns the median value |
| min | Returns the minimum value |
| sum | Returns the sum of values |
| to_array | Returns an array of values |
// Returns the total number of users, the number of distinct users and the first login time in the USA
dataset = logins
| filter country = "USA"
| comp count username as totalUsers, count_distinct username as distinctUsers, earliest _time as firstLogin
// Returns the amount of logins per country
dataset = logins
| comp count correlationId as logins by country
config <option> = <value>
The config statement is used to set various options for the query execution. RQL comes with built-in options, but you can also add your own custom options for your application.
| Option | Description | Default |
|---|---|---|
| case_sensitive | Determine whether values are evaluated as case sensitive in filter statements |
true |
| grouping | Deprecated: Group results by a field in comp statement |
'' |
dataset = users
| config case_sensitive = false
| filter name contains "john"
dataset = <string>
The dataset statement sets the context for the query by specifying the dataset to be processed. This statement is not processed by RQL itself but is intended for use in your application to allow differentiation between multiple datasets. This can be especially handy if your application deals with multiple data sources or tables, and you want to apply RQL operations to a specific one.
dataset = transaction_logs | filter transactionID = "TX1001"
dedup <field1>[,<field2>, ...] by asc | desc <field>
The dedup statement is used to remove duplicate records based on field(s). By default it returns the first record, but you can specify the direction of the dedup using the asc (ascending) or desc (descending) keywords and some other field, such as timestamp to return chronologically latest record.
# Returns all the latest unique username + deviceName sign-in combinations
dataset = signInLogs
| filter location.country = "GB"
| dedup username, deviceName by _time desc
fields <field1> [as <alias1>], <field2> [as <alias2>], ...
The fields statement enables you to cherry-pick the fields you're interested in from your dataset. This becomes useful when dealing with data structures having multiple fields, and you want to limit the output to only a few specific ones. If you don't specify any fields, all fields will be returned.
You can optionally rename the fields in the output using the as keyword, providing an alias for the original field name.
dataset = customer_records
| filter customerID = "CUST1001"
| fields firstName as Name, emailID as Email
filter <field> = <value> [and|or] <field> = <value> ...
The filter statement is used to limit the dataset to records that match the specified criteria. You can compare fields to values using logical operators, and you can combine multiple criteria using the and and or keywords. For a list of supported operators, see the Operators section.
dataset = users
| filter age > 18 and email not contains "@gmail.com"
| filter country = "Canada" or country = "Spain"
| filter role in ("admin", "manager")
| fields name, age, country, email
limit <number>
The limit statement is used to limit the number of records returned in the result. This is useful for paging or returning a top N list.
dataset = logins
| filter country = "USA"
| sort username desc
| limit 10
| fields country, username
search <query>
The search statement is used to limit the dataset to records that match the specified query. This is useful for full-text search or searching for specific patterns in the data.
Compared to the filter statement, the search statement searches all fields in the dataset.
// find all users with "john" in their name or email
dataset = users
| fields name, email
| search "john"
sort <field> [asc|desc], <field> [asc|desc] ...
The sort statement is used to order the results by one or more fields. You can specify the direction of the sort using the asc (ascending) or desc (descending) keywords. If no direction is specified, the data will not be sorted.
dataset = users
| filter age > 18
| sort age desc, name asc
| fields name, age
- Fixed bug with invalid return field names in
compstatement
- Deprecated
groupingoption inconfigstatement - Added
by [field]argument tocompstatement to allow grouping by a field
- Fixed bug with
filterstatement treating field names ending withinor some other operators as list filter
- Removed ElasticSearch integration
- The ElasticSearch integration was removed due to the complexity and performance issues it introduced. The library is now focused on providing a lightweight and efficient query language for data manipulation without the overhead of ElasticSearch.
- Added functions:
ago()fnv1a()future()geo_in_polygon()md5()now()sha1()sha256()
- Renamed
distance()togeo_distance() - Fixed bug with
matchesfilter not handling regex flags properly
- Unified functions in
alterandfilterstatements- Both statements now support the same functions to modify fields
- Added
distance()function - Fixed bug with
searchstatement not working correctly with non-string values
- Fixed bug with
dedupfield parsing
- Added support for
inandnot inoperators infilterstatement
- Fixed small bug in ElasticSearch query execution
- Optimized ElasticSearch query execution
- Some dedup queries now use inner_hits to get the latest record, which improves performance especially in large datasets
- Removed debug logging from ElasticSearch query execution
- Optimized ElasticSearch query execution
- Some filters are now converted to ElasticSearch compatible filters, which should improve performance especially in large datasets
- Added
to_numberfunction toalterstatement - Improved test coverage
- Fixed bug in not equals operator in
filterstatement
- Fixed bug with inconsistent UUID filtering in
filterstatement
- Fixed bug with inconsistent date types (string vs Date) in
filterstatement- Now all date values are converted to
Dateobjects for consistency
- Now all date values are converted to
- Added support for relative date filtering in
filterstatement- Supported units:
s(seconds),m(minutes),h(hours),d(days) - Example:
filter date > -1h
- Supported units:
- Added filter value alias
now()for current date and time- Example:
filter date > now()
- Example:
- Improved date filtering consistency
- Breaking change: Reworked query parsing and execution logic
- Queries are now parsed in the order they are written in the query string, instead of being grouped by statement type
- This might break existing queries that rely on the old fixed order of statements
- This change makes the query execution more predictable and easier to understand and also allows chaining of statements in a more flexible way
- Chaining multiple
compfunctions must be done on one statement seperated by commas instead of multiplecompstatements
- Removed old deprecated
LegacyQueryExecutorandLegacyQueryParserclasses
- Hotfix: Fixed exports of QueryParser and QueryExecutor
- Added better functionality for
searchstatement - Added grouping option for
compstatement viaconfigstatement - Refactored codebase to improve maintainability and readability
- Deprecated old query execution and parsing logic and moved them to
LegacyQueryExecutorandLegacyQueryParser
- Added support for
searchstatement
- Added support for
configstatement - Added case-sensitive option to
filterstatement viaconfigstatement - Added support for single quotes in
filterstatement
- Hotfix for ElasticSearch scroll API not working correctly
- Changed ElasticSearch to use scroll API instead of search_after
- Re-enabled sorting for ElasticSearch queries
- Disabled sorting for ElasticSearch queries to fix issue with Elastic pre-document sorting
- Changed ElasticSearch to use search_after instead of hard coded body size
- Changed size to 10k for ElasticSearch search
- Removed ElasticSearch query limit, using default value instead
- Added ElasticSearch sorting to prevent missing results in larger datasets
- Changed ElasticSearch body size from 10k to 20k
- Added
to_stringfunction toalterstatement - Added
to_datefunction toalterstatement - Added
getfunction toalterstatement - Added
get_arrayfunction toalterstatement - Added
base64_encodeandbase64_decodefunctions toalterstatement - Added
round,ceilandfloorfunctions toalterstatement - Added
extract_url_hostfunction toalterstatement - Added
json_parseandjson_stringifyfunction toalterstatement - Changed execution order of
alterstatement to be executed beforefieldsstatement - Added support for dynamic fields in
substringfunction - Added support for line comments starting with
//
- Added
to_arrayfunction tocompstatement - Added
trimfunction toalterstatement - Added
splitfunction toalterstatement - Added
lengthfunction toalterstatement
- Fixed a bug where
dedupwould not work correctly if the field was not present in the dataset - Improved documentation
- Added support for null values in
filterstatement
- Added support for
compstatement- Added support for
avg,count,count_distinct,earliest,first,last,latest,max,median,min,sumfunctions
- Added support for
- Added support for
dedupstatement - Added support for line comments (starting a line with
#) - Added nested field support for
alterstatement - Arithmetic
alterfunctions now handle invalid fields as 0 instead of NaN - Added
coalescefunction toalterstatement - Added
incidrfunction toalterstatement
- Fixed a bug where nested field in
filterstatement was not working correctly if the field didn't exist
- Fixed a bug where OR operator was not working correctly in
filterstatement - Added
QueryParsingOptionsto QueryParser - Added option to disable dataset requirement via
strictDatasetoption
- Added support for
<=and>=operators - Added
incidrandnot incidroperators - Added alias
~=formatchesoperator - Fixed a bug where query couldn't contain multiple
filterstatements - Improved test coverage for QueryExecutor
- Cleaned test code
- Updated dependencies
This project is licensed under the GNU GPLv3 License - see the LICENSE file for details.