xlucene-parser / parser / Parser
Class: Parser
Defined in: packages/xlucene-parser/src/parser.ts:35
Parse a xLucene query and provide methods to traverse and manipulate the resulting AST.
The Parser class is the main entry point for parsing xLucene queries. It converts query strings into an Abstract Syntax Tree (AST) that can be traversed, validated, and transformed.
Example
const parser = new Parser('name:John AND age:>=25');
console.log(parser.ast); // Access the parsed AST
// Iterate over term nodes
parser.forTermTypes((node) => {
console.log(node.field, node.value);
});
// Resolve variables
const resolved = parser.resolveVariables({ minAge: 25 });
Constructors
Constructor
new Parser(
query
,options?
,_overrideNode?
):Parser
Defined in: packages/xlucene-parser/src/parser.ts:68
Create a new Parser instance.
Parameters
Parameter | Type | Description |
---|---|---|
query | string | The xLucene query string to parse |
options? | ParserOptions | Optional configuration for parsing behavior |
_overrideNode? | Node | Internal parameter for creating parser with existing AST |
Returns
Parser
Example
// Basic parsing
const parser = new Parser('name:John');
// With type configuration
const parser = new Parser('age:25', {
type_config: { age: 'integer' }
});
// With variable filtering
const parser = new Parser('name:$username', {
filterNilVariables: true,
variables: { username: 'John' }
});
Properties
Property | Modifier | Type | Defined in |
---|---|---|---|
ast | readonly | Node | packages/xlucene-parser/src/parser.ts:36 |
filterNilVariables | readonly | boolean | packages/xlucene-parser/src/parser.ts:39 |
query | readonly | string | packages/xlucene-parser/src/parser.ts:37 |
typeConfig | readonly | xLuceneTypeConfig | packages/xlucene-parser/src/parser.ts:38 |
Methods
filterNodes()
filterNodes(
ast
,fn
):Node
Defined in: packages/xlucene-parser/src/parser.ts:156
Recursively filters nodes in an AST based on a predicate function. Handles logical groups, conjunctions, negations, ranges, and function nodes while preserving tree structure and automatically simplifying when possible (e.g., unwrapping single-node conjunctions).
Parameters
Parameter | Type | Description |
---|---|---|
ast | Node | The root AST node to filter |
fn | (node , parent? ) => boolean | Predicate function that receives (node, parent) and returns true to keep the node, false to remove it |
Returns
New filtered AST containing only nodes that pass the filter criteria. Returns empty node if all nodes are filtered out.
Examples
// Filter out unwanted fields
const filtered = filterNodes(ast, (node) => node.field !== 'unwanted');
// Filter based on parent context
const filtered = filterNodes(ast, (node, parent) =>
!parent || utils.isLogicalGroup(parent)
);
forEachFieldValue()
forEachFieldValue(
cb
):void
Defined in: packages/xlucene-parser/src/parser.ts:452
Iterate over all field values from term-like nodes.
This method extracts and processes all field values from nodes that contain searchable terms. It's particularly useful for validating values and variables, or for collecting all values used in a query.
Parameters
Parameter | Type | Description |
---|---|---|
cb | (value , node ) => void | Callback function called for each field value |
Returns
void
Example
// Collect all literal values
const values: any[] = [];
parser.forEachFieldValue((value, node) => {
if (value.type === 'value') {
values.push(value.value);
}
});
// Validate variable references
parser.forEachFieldValue((value, node) => {
if (value.type === 'variable') {
console.log(`Variable ${value.value} used in field ${node.field}`);
}
});
forEachTermNode()
forEachTermNode(
fieldValidator
,valueValidator
):void
Defined in: packages/xlucene-parser/src/parser.ts:474
Parameters
Parameter | Type |
---|---|
fieldValidator | (field ) => void |
valueValidator | (fieldValue ) => void |
Returns
void
forTermTypes()
forTermTypes(
cb
,skipFunctionParams
):void
Defined in: packages/xlucene-parser/src/parser.ts:412
Iterate over all term-like nodes in the AST.
Term-like nodes include: Term, Regexp, Range, Wildcard, Function, and TermList. This is a convenience method that filters to nodes representing searchable terms.
Parameters
Parameter | Type | Default value | Description |
---|---|---|---|
cb | (node ) => void | undefined | Callback function called for each term-like node |
skipFunctionParams | boolean | true | Whether to skip traversing function parameters (default: true) |
Returns
void
Example
// Process all searchable terms
parser.forTermTypes((node) => {
if (node.field) {
console.log(`Field: ${node.field}`);
}
});
// Include function parameters in traversal
parser.forTermTypes((node) => {
console.log('Term type:', node.type);
}, false);
forTypes()
forTypes<
T
>(types
,cb
,skipFunctionParams
):void
Defined in: packages/xlucene-parser/src/parser.ts:299
Recursively iterate over all nodes of the specified types in the AST.
This method performs a depth-first traversal of the AST, calling the callback function for each node whose type matches one of the specified types.
Type Parameters
Type Parameter |
---|
T extends readonly NodeType [] | NodeType [] |
Parameters
Parameter | Type | Default value | Description |
---|---|---|---|
types | T | undefined | Array of NodeType values to match |
cb | (node ) => void | undefined | Callback function called for each matching node |
skipFunctionParams | boolean | false | Whether to skip traversing function parameters |
Returns
void
Example
// Find all term and wildcard nodes
parser.forTypes([NodeType.Term, NodeType.Wildcard], (node) => {
console.log('Found node:', node.type);
});
// Find logical groups, skipping function parameters
parser.forTypes([NodeType.LogicalGroup], (node) => {
console.log('Logical group with', node.flow.length, 'conjunctions');
}, true);
mapNode()
mapNode(
fn
):Node
Defined in: packages/xlucene-parser/src/parser.ts:625
Transform the AST by applying a mapping function to each node.
This method performs a deep traversal of the AST, applying the provided function to each node and rebuilding the tree with the results. The function receives each node and its parent, and should return a transformed node.
Parameters
Parameter | Type | Description |
---|---|---|
fn | (node , parent? ) => Node | Function to transform each node |
Returns
The transformed AST root node
Example
// Transform all string values to lowercase
const transformedAST = parser.mapNode((node, parent) => {
if (node.type === 'term' && node.value.type === 'value') {
return {
...node,
value: {
...node.value,
value: String(node.value.value).toLowerCase()
}
};
}
return node;
});
resolveVariables()
resolveVariables(
variables
):Parser
Defined in: packages/xlucene-parser/src/parser.ts:566
Validate and resolve variables in the query, returning a new Parser instance.
This method processes all variable references in the AST, replacing them with
their actual values. Variable references use $variableName
syntax, and scoped
variables use @variableName
syntax.
Parameters
Parameter | Type | Description |
---|---|---|
variables | xLuceneVariables | Object mapping variable names to their values |
Returns
Parser
A new Parser instance with resolved variables
Example
// Original query with variables
const parser = new Parser('name:$username AND age:>=$minAge');
// Resolve variables
const resolved = parser.resolveVariables({
username: 'John',
minAge: 25
});
// Resolved query equivalent to: name:John AND age:>=25
Throws
If variables object is invalid
walkAST()
walkAST(
cb
):void
Defined in: packages/xlucene-parser/src/parser.ts:362
Recursively walk through every node in the AST and call the callback function for each node.
This method performs a depth-first traversal of the entire AST, visiting every node
exactly once. Unlike forTypes()
which filters by node type, this method calls the
callback for all nodes regardless of their type.
Parameters
Parameter | Type | Description |
---|---|---|
cb | (node ) => void | Callback function called for each node in the AST |
Returns
void
Example
// Log all nodes in the AST
parser.walkAST((node) => {
console.log(`Node type: ${node.type}`);
});
// Search for node properties
parser.walkAST((node) => {
if (isFunctionNode(node) && node.name === 'knn') {
hasKNN = true;
return;
}
});