索引
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
}