Index(索引)

index 映射参数通过控制字段是否包含在倒排索引中,来决定其是否可搜索。当设置为 true 时,字段被索引并可被查询。当设置为 false 时,字段存储在文档中但未被索引,使其不可搜索。如果您不需要搜索某个特定字段,禁用该字段的索引可以减少索引大小并提高索引性能。例如,您可以对仅用于显示的大文本字段或元数据禁用索引。

默认情况下,所有字段类型都会被索引。

支持的数据类型

index 映射参数可以应用于以下数据类型:

在字段上启用索引

以下请求创建一个名为 products 的索引,其中 description 字段被索引(默认行为):

PUT /products
{
  "mappings": {
    "properties": {
      "description": {
        "type": "text"
      }
    }
  }
}

使用以下请求索引一个文档:

PUT /products/_doc/1
{
  "description": "This product has a searchable description."
}

查询 description 字段:

POST /products/_search
{
  "query": {
    "match": {
      "description": "searchable"
    }
  }
}

以下响应确认索引的文档已成功被查询匹配:

{
  ...
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 0.2876821,
    "hits": [
      {
        "_index": "products",
        "_id": "1",
        "_score": 0.2876821,
        "_source": {
          "description": "This product has a searchable description."
        }
      }
    ]
  }
}

在字段上禁用索引

创建一个名为 products-no-index 的索引,其中 description 字段未被索引:

PUT /products-no-index
{
  "mappings": {
    "properties": {
      "description": {
        "type": "text",
        "index": false
      }
    }
  }
}

使用以下请求索引一个文档:

PUT /products-no-index/_doc/1
{
  "description": "This product has a non-searchable description."
}

使用 description 字段查询 products-no-index

POST /products-no-index/_search
{
  "query": {
    "match": {
      "description": "non-searchable"
    }
  }
}

以下错误响应表明搜索查询失败,因为 description 字段未被索引:

{
  "error": {
    "root_cause": [
      {
        "type": "query_shard_exception",
        "reason": "failed to create query: Cannot search on field [description] since it is not indexed.",
        "index": "products-no-index",
        "index_uuid": "yX2F4En1RqOBbf3YWihGCQ"
      }
    ],
    "type": "search_phase_execution_exception",
    "reason": "all shards failed",
    "phase": "query",
    "grouped": true,
    "failed_shards": [
      {
        "shard": 0,
        "index": "products-no-index",
        "node": "0tmy2tf7TKW8qCmya9sG2g",
        "reason": {
          "type": "query_shard_exception",
          "reason": "failed to create query: Cannot search on field [description] since it is not indexed.",
          "index": "products-no-index",
          "index_uuid": "yX2F4En1RqOBbf3YWihGCQ",
          "caused_by": {
            "type": "illegal_argument_exception",
            "reason": "Cannot search on field [description] since it is not indexed."
          }
        }
      }
    ]
  },
  "status": 400
}