QPL Parsing, uses a custom grammar implemented with LARK,  a modern general-purpose parsing library for Python, with it we can parse the query using the grammar and a LALR(1) parser.

Parsing a Query

Parsing a query with QPL is as simple as it gets:

  1. Import the QPLOptions and the QPLParser
  2. Generate an instance of QPLOptions,
    1. The 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.
    2. The wildcard options, accepts a boolean, in case of True, a new rule to identify wildcards will be added
  3. Generate an instance of the QPLParser, and pass the options to it
  4. Parse the query by using the function from the parser, parse_query, this will return a qpl_query


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)

# Parse the query into a qpl_query
qpl_query = parser.parse_query('This is PyQPL')

print(qpl_query)

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

or(terms(This,is,PyQPL))

QPL Tree

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

# Parse the query into a qpl_tree
qpl_tree = parser._parse('This is PyQPL')

print(qpl_tree.pretty())

You can get the qpl_query from the qpl_tree with qpl_tree.operator

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

or
  term	This
  term	is
  term	PyQPL


Custom Grammar

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 

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

  • No labels