Parsing a query with QPL is as simple as it gets, we start by importing :
Code Block | ||||
---|---|---|---|---|
| ||||
from pyqpl.qpl import QPLOptions
from pyqpl.parser import QPLParser |
QPLOptions is the one which will said the grammar to use and the rules to apply,
Code Block | ||||
---|---|---|---|---|
| ||||
options = QPLOptions(fields='content', implicit_operator='or', wildcard=False) |
implicit_operator
option, accepts either 'or' or 'and', this option select grammars with a slight variation between them, to set the operator (or / and) as the implicit operation.wildcard
options, accepts a boolean, in case of True, a new rule to identify wildcards will be addedCode Block | ||||
---|---|---|---|---|
| ||||
from pyqpl.qpl import QPLOptions
from pyqpl.parser import QPLParser
# Generate QPLOptions
options = QPLOptions(fields='content', implicit_operator='or', wildcard=False)
# Generate Parser
parser = QPLParser(options=options) |
With the parser created, parse the query with the line bellow
Code Block | ||||
---|---|---|---|---|
| ||||
# Parse the query into a qpl_query qpl_query = parser.parse_query('This is PyQPL') print(qpl_query) |
Info |
---|
The qpl_query will be an object of type Operator, which will contain all the operators of the query. At this point the qpl query is truly engine agnostic, and it needs a translator to be an engine query |
The string representation of the qpl_query will look like this
Code Block |
---|
or(terms(This,is,PyQPL)) |
If for some reason, you require a more effective way to understand the query you can call the function _parse instead of parse_query, this will return a qpl_tree, this is a previuos step before returning the qpl_query
Code Block | ||||
---|---|---|---|---|
| ||||
# Parse the query into a qpl_tree
qpl_tree = parser._parse('This is PyQPL')
print(qpl_tree.pretty()) |
Info |
---|
You can get the qpl_query from the qpl_tree with qpl_tree.operator |
Info |
---|
The function .pretty() of the QPL tree will show a visual representation of how the query is form |
The string representation of the qpl_tree will look like above, a more "graphical" way to see how the query is composed
Code Block |
---|
or
term This
term is
term PyQPL |
Warning |
---|
We do not recommend the use of a custom grammar. This functionality exist for grammar, fixes, enhancements or additions to projects which can not wait for an official release. A wrong grammar could break the entire functionality. That said, you require to modify the existen grammar, or require a new one, please contact the development team. |
You can use your own grammar to parse a query, with either a well made lark file, or a raw string
Code Block | ||||
---|---|---|---|---|
| ||||
options = QPLOptions(fields='content', grammar='/grammar/mygrammar.lark') |
For more detail on how to build a grammar please check Grammar Composition from the Lark documentation