4

I am trying to write a simple regexp query using elasticsearch in python that just won't work. Can anybody tell me where I'm going wrong ?

result = es.search(index="my-index", body={"query": {"regexp": {"Name": "Vi.*" }}})

The indexed document is a list of names with my name also in it (Vitthal Bhandari). The above query always yields empty results when it should return my name instead. The document is properly indexed and other queries work just fine. For instance a match query gives the required result.

result = es.search(index="my-index", body={"query": {"match": {"Name": "Vitthal" }}})

What is the problem with the regexp query that I'm writing that it won't give any result? Any suggestions?

**EDIT : ** The "Name" mapping is given below :

"Name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
1
  • Add a sample document and mapping of name also Commented Jun 23, 2020 at 8:54

2 Answers 2

3

As per your mapping

"Name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        }

You have default analyzer

To make it work:

{"query": {"regexp": {"Name": "vi.*" }}}

Use lower case.

Reason for Vi.* not working:

regexp is a term query. It is not a full text search query.

Unlike full-text queries, term-level queries do not analyze search terms. Instead, term-level queries match the exact terms stored in a field.

So, it expects terms starting with Vi in the index which is not true as it is analysed and stored as vi..

Reference

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

2 Comments

Thanks for the solution. It worked. While we're at it can you help me with another thing. The next step in my program is to get the search string as an input from the user, i.e., in above example the string "Vi" is to be taken as input from user at run time. Let's say the string is stored in a variable str. How do I formulate a query using str ?
Please reply to my comment at here
1

Use

{
  "query": {
    "regexp": {
      "Name": "vi.*"
    }
  }
}

or

{
  "query": {
    "regexp": {
      "Name.keyword": "Vi.*"
    }
  }
}

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.