Python: How to input a string and use it as query match elasticsearch

Hi everyone,
I'm trying to code a simple python script which should ask for a string to be inserted by shell and use it as "match string" in a match query. I post here the script so the problem can be better understandable.

client = Elasticsearch()

query_string = raw_input("Enter your query string: ")
print(query_string)

s = Search(using=client, index="enron_test"
    .query("match", message_body=query_string))

response = s.execute()

Actually, I should get all the json documents (each represents an email) which contain the string "query_string" in the message_body field.

The problem is that when I run the script, I get this error: AttributeError: 'str' object has no attribute 'query'.
I'm a newbie in Elasticsearch, where am I wrong?

I think you have a typo in your code and that one of the closing parenthesis is misplaced. Try this instead:

s = Search(using=client, index="enron_test")
    .query("match", message_body=query_string)
1 Like

@timost It works!!!

EDIT:
I was trying to print the result of the query and I figured out that I cannot retrieve hit.from of the json document.
It tells me SyntaxError: invalid syntax.

Here is the code:

for hit in response:
    print(hit.from)
    print(hit.to)
    print(hit.message_body)
    print(line + "\n")

The from field is highlighted in grey.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.