@repositive/query-parser



The purpose of this library is to transform a search string to a tokenized data structure that can be used to perform analysis on the search input or as an intermediate structure to translate the query into other DSLs or query structures.
Features:
- Basic boolean algebra operators (
AND
, OR
, NOT
)
- Implicit intersections (
AND
) on non quoted spaces. - Logic grouping with parens
(white or blue) flower not thistle
- Exact match between quoted strings on non predicated tokens.
flower "white daisy"
- Predicated/Filtered search
family:Asteraceae population:>100000 england
Installation
With npm:
$ npm i @repositive/query-parser
Available Serializers
- Natural Language String
- ElasticSearch 2.x
Usage
The library exposes the following functions:
Tree construction
- token:
(str: string) => Token
- predicate:
({key: string, value: string}) => Predicate
- and:
<L extends Node, R extends Node>({left: L, right: R}) => AND<L, R>
- or:
<L extends Node, R extends Node>({left: L, right: R}) => OR<L, R>
- not:
<N extends Node>(negated: N) => NOT<N>
Tools
- fold:
<R>(node: Node, f: (node: Node, l: R, r: R) => R, R) => R
- filter:
<R> (node: Node, f: (node: Node) => node is R) => R[]
- path:
(node: Node, target: Node) => Node[]
- remove:
(node: Node, target: Node) => Node
- replace:
({on: Node, target: Node, replacement: Node}) => Node
Parsing natural language string
- fromNatural:
(str: string) => Node
Parses the current string and returns a boolean binary tree representing the search.
Serialization
- toNatural:
(tree: Node) => string
Serializes a boolean binary tree into a string emulating how a human would write it. - toElastic2:
(tree: Node) => any
Serializes the boolean binary tree into a elasticsearch 2.x query.
import QP from 'npm:@repositive/query-parser';
const tree = QP.fromNatural('is:user Istar NOT profession:developer')
const profession = QP.filter(tree, (n) => n.key === 'profession')[0];
const professional = QP.remove(tree, profession);
const awesome = QP.and({left: professional, right: QP.predicate({key: 'attribute', value: 'awesome'}));
const newQueryString = QP.toNatural(awesome);