Pawan Kumar Singh
Pawan Kumar Singh

Reputation: 21

Startwith Query (without phrase) in elasticsearch

Following are the sample available data:

Following are the queries that I have tried:

  1. Prefix, which gives us startwith + phrase only. Like If I search for car for airport, we will not be getting results like "car hire for airport service" or car hire for airport pickup.

    Sample Query:

    "query": {
     "bool": {
      "must": [
        {
          "prefix": {
            "sfield.exact": {
              "value": "car hire"
            }
          }
        }
      ]
    }
    

    }

  2. Tried match_phrase_prefix, this also runs similar to prefix

Sample Query:

"query": {
    "bool": {
      "must": [
        {
          "match_phrase_prefix": {
            "sfield": {
              "value": "car hire"
            }
          }
        }
      ]
    }
  }
  1. Combination of Prefix and query_string, I have tried matching first word using prefix and rest of the words using query_string (because sometime I need to match partial matches also, like "car for air*").

Sample Query:

"query": {
        "bool": {
          "must": [
            {
              "prefix": {
                "sfield.exact": {
                  "value": "car "
                }
              }
            },
            {
              "query_string": {
                "default_field": "sfield",
                "query": "car hire*",
                "default_operator": "AND"
              }
            }
          ]
        }
      }

Point 3 works well, but takes a lot of time while executing for the first time.. Before This query was returning fast result, but now it is responding slowly.. I have used field type as "text" (for query_string searches) and "keyword" (for prefix searches), and my total data size is approximately 60 GB, and my application is created using PHP..

Please let me know, if there are any way to fetch startwith + all words matched (including partial matches) in lesser time..

Sample mapping

"mappings": {
    "ctype": {
        "_all":       { "enabled": false  },
        "properties": {
            "id": { "type": "long" },
            "cname": { "type": "text" },
            "sfield": {
                "type": "text",
                "fields": {
                    "exact": {
                        "type": "keyword"
                    }
                }
            }
        }
    }
}

Upvotes: 1

Views: 132

Answers (1)

Eli
Eli

Reputation: 4936

If I understand correct, you just want the start with option. So I'll recommend you to use wildcard:

"query": {
 "bool": {
  "must": [
    {
      "wildcard": {
        "sfield.exact": "car hire*"
      }
    }
  ]
}

See Wildcard

Upvotes: 0

Related Questions