2

I am trying to write a django app and use elasticsearch in it with elasticsearch-dsl library of python. I don't want to create all switch-case statements and then pass search queries and filters accordingly.

I want a function that does the parsing stuff by itself. For e.g. If i pass "some text url:github.com tags:es,es-dsl,django", the function should output corresponding query.

I searched for it in elasticsearch-dsl documentation and found a function that does the parsing. https://github.com/elastic/elasticsearch-dsl-py/search?utf8=%E2%9C%93&q=simplequerystring&type= However, I dont know how to use it. I tried s = Search(using=client).query.SimpleQueryString("1st|ldnkjsdb"), but it is showing me parsing error.

Can anyone help me out?

2
  • As of now, your question is unclear. Please clarify a little bit more what you mean - You want to pass in a query string, and receive what in return? The results of the query? A query object? Commented May 22, 2018 at 19:24
  • Have you tried to write any code yourself? If you have, please edit your post to include it. Commented May 22, 2018 at 19:27

2 Answers 2

2

You can just plug the SimpleQueryString in the Search object, instead of a dictionary send the elements as parameters of the object.

from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
from elasticsearch_dsl.query import SimpleQueryString

client = Elasticsearch()
_search = Search(using=client, index='INDEX_NAME')

_search = _search.filter( SimpleQueryString(
     query = "this + (that | thus) -those", 
     fields= ["field_to_search"],
     default_operator= "and"
))

A lot of elasticsearch_dsl simply change the dictionary representation to classes of functions that makes the code look pythonic, and avoid the use of hard-to-read elasticsearch JSONs.

Sign up to request clarification or add additional context in comments.

Comments

0

Im guessing you are asking about the usage of elasticsearch-dsl with query string like you are making a request with json data to the elasticsearch api. If that's the case, this is how you are going to use elasticsearch-dsl:

assume you have the query in query variable like this:

{
    "query": {
        "query_string" : {
            "default_field" : "content",
            "query" : "this AND that OR thus"
        }
    }
}

and now do this:

es = Elasticsearch(
    host=settings.ELASTICSEARCH_HOST_IP, # Put your ES host IP
    port=settings.ELASTICSEARCH_HOST_PORT, # Put yor ES host port
)
index = settings.MY_INDEX # Put your index name here
result = es.search(index=index, body=query)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.