GitHub Logo

search-expression-parser

Turn a search expression like this:
...into an easily processable tree structure like this:


Installation

To install search-expression-parser, simply run:
npm install search-expression-parser

Usage

The following parses a search expression and logs the result to the console:
import { parse } from 'search-expression-parser';

const mySearchExpression = 'name:john AND age:50';
const parserResult = parse(mySearchExpression);

if (parserResult.success) {
console.log('Success!', parserResult);
} else {
console.error('Something went wrong...');
}

Often, search-expression-parser is used to filter elements from an array. To do this, you could either manually traverse the parsed search expression. Or, simply use the built-in helper function for this:
import { filter } from 'search-expression-parser';

// ...

function filterMyData(parsedSearchExpression) {
const myData = [1, 2, 3, 4];
const filteredData = filter(myData, parsedSearchExpression, dataMatcher);

console.log(filteredData);
}
function dataMatcher(expressionNode, item) {
/*
Depending on the data in the node, we can perform filtering.
In this example, we want to allow queries that look like this:
num:1 OR num:2 OR NOT num:5

The DataMatcher function may get called on two types of nodes:
- Key-Value nodes like “name:bob”
- Value-Only nodes like “bob”

In this example, we want to treat Value-Only nodes as invalid (i.e. as a syntax error).
Also, we want to treat keys of a Key-Value node as a syntax error
if the key is not “num”.
*/

The error reporting feature of the filter function only gets called when a particular node is visited. Thus, it is not suited for cases where you want to validate the entire search tree. In general, the built-in filter function is great if you want to implement simple search features. However, for more complex functionalities (e.g. type-safe validation right after the parsing step), it might be necessary to directly work with the search tree.

Grammar

Search expressions are pretty versatile. In the following, you can find a list of examples that show the possible search expressions. The examples are interactive, so you can always make changes to them if you like!

One simple value


One key-value pair


A key without a value

When building features like auto-completion or suggestions, it is important that the parser does not simply error out if a value is missing after the colon. That's why search-expression-parser allows empty values after a colon.

Text with spaces


Complex boolean expression