ElasticSearch: How to search for a value in any fi

2020-08-26 03:40发布

问题:

I have two indices my_index_1 and my_index_2. Within these indices, I have the following document types:

my_index_1:

  • people
  • organizations
  • roles
  • skills

my_index_2:

  • products
  • services
  • patents
  • trademarks
  • servicemarks

Each of the types has different fields.

My Question: What is the best way to query for the string "abc" in any field of any type, across any one or even both indices?

I don't see anything in the documentation that facilitates such a search. Is there something that might look like:

$ curl -XPOST 'localhost:9200/_search?pretty' -d '
{
  "query": { "match": { *: "abc" } }
}'

Thanks, in advance, for any help you can offer.

回答1:

Either the query_string query or the match query would be what you're looking for.

query_string will use the special _all field if none is specified in default_field, so that would work out well.

curl -XPOST 'localhost:9200/_search?pretty' -d '{
  "query": { "query_string": { "query": "abc" } }
}'

And with match you can just specify the _all as well.

curl -XPOST 'localhost:9200/_search?pretty' -d '{
  "query": { "match": { "_all": "abc" } }
}'

Note that with query_string you may use wildcards, which you can't with match


UPDATE:

As the _all field was deprecated in 6.0, the solution is now to implement a custom all field



回答2:

An alternative to the now deprecated _all field is the multi match query

GET /_search
{
  "query": {
    "multi_match" : {
      "query":    "Will Smith",
      "fields": [ "important_field^5", "less_important^2", "title", "*_name" ] 
    }
  }
}

Note wildcards in the field names are supported as well as boosting a fields importance with the ^# syntax

As of version 7.3: If no fields are provided, the multi_match query defaults to the index.query.default_field index settings, which in turn defaults to *. * extracts all fields in the mapping that are eligible to term queries and filters the metadata fields. All extracted fields are then combined to build a query.

Another alternative is the Query string query

GET /_search
{
    "query": {
        "query_string" : {
            "query" : "(new york city) OR (big apple)",
            "default_field" : "content"
        }
    }
}

default_field (Optional, string) Default field you wish to search if no field is provided in the query string.

Defaults to the index.query.default_field index setting, which has a default value of *.



回答3:

I think you can use _all for this purpose

Try this

$ curl -XPOST 'localhost:9200/_search?pretty' -d '
{
  "query": { "match": { "_all": "abc" } }
}'

You could also use query_string as it searches against _all by default.