Skip to content
章节导航

match 高级用法:多字段匹配和短语搜索

多字段搜索匹配

  • 业务查询,需要在多个字段上进行文本搜索,用 multi_match
  • 在 match 的基础上支持对多个字段进行文本查询匹配

语法格式

shell
GET /index/_search
{
  "query": {
    "multi_match": {
      "query": "要搜索的文本",
      "fields": ["字段1", "字段2", ...]
    }
  }
}

# query:需要匹配的查询文本。
# fields:一个包含需要进行匹配的字段列表的数组。

短语搜索匹配

  • 是 Elasticsearch 中提供的一种高级匹配查询类型,用于执行精确的短语搜索
  • 相比于 match 查询,match_phrase 会在匹配时考虑到单词之间的顺序和位置

语法格式

shell
GET /index/_search
{
  "query": {
    "match_phrase": {
      "field_name": {
        "query": "要搜索的短语"
      }
    }
  }
}

# field_name:要进行匹配的字段名。
# query:要搜索的短语。

数据环境准备

创建索引库

shell
PUT /product_v2
{
  "settings": {
    "number_of_shards": 2,
    "number_of_replicas": 0
  },
  "mappings": {
    "properties": {
      "product_name": {
        "type": "text"
      },
      "description": {
        "type": "text"
      },
      "category": {
        "type": "keyword"
      }
    }
  }
}

批量插入数据

shell
POST /product_v2/_bulk
{ "index": { "_index": "product_v2", "_id": "1" } }
{ "product_name": "iPhone 12", "description": "The latest iPhone model from Apple", "category": "electronics" }
{ "index": { "_index": "product_v2", "_id": "2" } }
{ "product_name": "Samsung Galaxy S21", "description": "High-performance Android smartphone", "category": "electronics" }
{ "index": { "_index": "product_v2", "_id": "3" } }
{ "product_name": "MacBook Pro", "description": "Powerful laptop for professionals", "category": "electronics" }
{ "index": { "_index": "product_v2", "_id": "4" } }
{ "product_name": "Harry Potter and the Philosopher's Stone", "description": "Fantasy novel by J.K. Rowling", "category": "books" }
{ "index": { "_index": "product_v2", "_id": "5" } }
{ "product_name": "The Great Gatsby", "description": "Classic novel by F. Scott Fitzgerald", "category": "books" }

多字段搜索案例

  • 在 product_name 和 description 字段上执行了一个 multi_match 查询
  • 将查询文本设置为 "iPhone",对这两个字段进行搜索,并返回包含匹配到的文档,这个是 OR 的关系,会有最佳匹配
shell
GET /product_v2/_search
{
  "query": {
    "multi_match": {
      "query": "iPhone",
      "fields": ["product_name", "description"]
    }
  }
}

短语搜索案例

  • 使用 match_phrase 查询在 description 字段上执行了一个短语搜索将要搜索的短语设置为 "classic novel"。
  • 使用 match_phrase 查询,Elasticsearch 将会返回包含 "classic novel" 短语的文档
shell
#match_phrase短语搜索
GET /product_v2/_search
{
  "query": {
    "match_phrase": {
      "description": "classic novel"
    }
  }
}

#match搜索,会进行分词
GET /product_v2/_search
{
  "query": {
    "match": {
      "description": "classic novel"
    }
  }
}