0

In my application, we have a search bar where a user can enter either first name, last name, ID, or an Email address. I am querying on User's data which is having the following fields, First Name, Last Name, ID, Email

For querying the first name, last name, and ID, I am querying like this-

{ 
   "query":{ 
       "query_string" : {"fields" : ["FName", "LName", "ID"], "query" : "Value entered by user*"}
   }
}

For querying an Email address, I want an exact match and I am querying like this-

{
    "query": {
        "bool": {
            "must": [{
                "match": {
                    "Mail": "Value entered by user"
                }
            }]
        }
    }
}

I have two questions here-

  1. How can I combine the above two queries into one, that can provide me results of users whose First Name, Last name, ID, or Email matches with whatever is entered in the search bar?
  2. How to extract only those users whose First Name, Last Name, ID, and Email exist in the database. For eg., if a user's detail matches with the search text but if its Email address isn't in the database, I don't want to show it.
Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42

1 Answers1

1

If I understand correctly, your query is

(search term should match ID,FName,LName OR search term should exact match Mail) AND all fields should exist for the document

This could be achieved by bool queries

GET test_index/_search
    {
      "query": {
        "bool": {
          "must": [
            {
              "bool": {
                "should": [
                  {
                    "query_string": {
                      "fields": [
                        "FName",
                        "LName",
                        "ID"
                      ],
                      "query": "jane*"
                    }
                  },
                  {
                    "match": {
                      "Mail": "jane"
                    }
                  }
                ]
              }
            },
            {"exists": {"field": "Mail"}},
            {"exists": {"field": "FName"}},
            {"exists": {"field": "LName"}},
            {"exists": {"field": "ID"}}
          ]
        }
      }
    }

Also, I assume that the Mail field is of type keyword and hence did not change the query that you provided in the question. If it is not, then for exact match you would need a keyword field. If you did not provide any analyzer explicitly then you should use Mail.keyword

Barkha Jain
  • 758
  • 5
  • 14