[Python] Validating ES query_string upfront, namely without connecting to an Elasticsearch...

Discussão em 'Python' iniciado por Stack, Julho 16, 2025.

  1. Stack

    Stack Membro Participativo

    I am looking for a Python library (if any) that could help validate the query_string field of Elasticsearch queries1 upfront, namely without connecting to an Elasticsearch server and without having to define any custom validation logic. 1I mean queries of the kind

    {
      "query": {
        "query_string": {
          "query": query_string
        }
      }
    }


    To give a clearer picture, I'd like to implement a simple utility that - based on a library of the kind described above - can help me build and let pass tests like the ones below:

    @pytest.mark.parametrize(
      "data, expectation",
      [
        (
          ['("Extended Reality" AND "Mixed Reality")'],
          None
        ),
        # missing closed parenthesis
        (
          ['("Extended Reality" AND "Mixed Reality"'],
          pytest.raises(ValueError)
        ),
        # empty query
        ([''], pytest.raises(ValueError)),
        # invalid query
        (
          ['("Extended Reality" AND'],
          pytest.raises(ValueError)
        ),
      ],
    )


    I've tried to follow the suggestions of LLM-based tools which, however, have been proven wrong. For instance, I've tried out different suggested options exploiting elasticsearch_dsl and either the class Query

    Query(query_str).to_dict() != {None: {}}


    or classes Q and Search in combination

    query = Q('query_string', query=query_string)
    search=Search().query(query)
    search.to_dict() != {None: {}}


    , but none of them do work (as indeed elasticsearch_dsl is not meant for validation). Thank you!

    Continue reading...

Compartilhe esta Página