网站建设

Elasticsearch常用查询

kibana管理面板->analytics->discover的查询中,筛选语言有两个,kql和lucene,在进行文档搜索的时候,注意切换对应语言。

kibana管理面板->management->开发工具中,可以执行更多语句,比如增删查改操作。

Elasticsearch RESTful API 请求

下面我整理一下常用的查询脚本

查看索引结构

# 获取索引基本信息
GET 索引名

# 用于整体确认索引是否存在,及结构概要(复制一个空表,需要用到)
GET 索引名/_mapping

# 用于查看索引参数配置
GET 索引名/_settings

添加

# 添加字段
PUT 索引名/_mapping
{
  "properties": {
    "字段名": {
      "type": "date"
    }
  }
}

# 添加索引
PUT 索引名
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 1,
    "refresh_interval": "30s"
  },
  "mappings": {
    "properties": {
      "字段名": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      }
    }
  }
}

给字段赋值

POST 索引名/_update_by_query
{
  "script": {
    "source": "ctx._source.字段名 = 1733011200000L"
  },
  "query": {
    "match_all": {}
  }
}
在批量执行任务的时候,文档数量往往过多,而导致执行脚本超时
这个时候,可以考虑分批执行
在 _update_by_query,请求中,batch_size
参数不适用于 Elasticsearch 7.x 和更高版本,这可能是导致错误的原因。要实现批量更新,可以使用 scroll_size
参数代替,或通过其他优化方法分批处理文档

POST 索引名/_update_by_query?scroll_size=500{
  "script": {
    "source": "ctx._source.字段名 = 1733011200000L"
  },
  "query": {
    "match_all": {}
  }}

按条件查询

# 查询有连续????号的文档
GET /索引名/_search
{
  "size": 10,
  "query": {
    "regexp": {
      "字段名": "*????*"
    }
  }
}

#查询字段中只有关键词的文档
GET 索引名/_search
{
  "query": {
    "term": {
      "字段名.keyword": "关键词"
    }
  }
}

# 查询在指定日期之后的文档
GET /索引名/_search
{
  "query": {
    "range": {
      "timestamp": {
        "gt": "2025-01-01"
      }
    }
  }
}

按条件删除

# 删除字段中只有关键词的文档
POST 索引名/_delete_by_query
{
  "query": {
    "term": {
      "字段名.keyword": "关键词"
    }
  }
}

# 删除在指定日期之后的文档
POST /索引名/_delete_by_query
{
  "query": {
    "range": {
      "timestamp": {
        "gt": "2025-01-01"
      }
    }
  }
}

下面是python的演示脚本

【执行查询】
response = es.search(index="索引名", body=执行语句)

【执行删除】
response = es.delete_by_query(index="索引名", body=执行语句)


# 构建查询
query = {
	"query": {
		"bool": {
			"must": [
				{
					"regexp": {
						# 查找包含4个或更多连续问号的记录
						"字段名.keyword": ".*\\?{4,}.*"
					}
				}
			]
		}
	},
	"size": 100  # 控制返回记录数量
}
# 执行查询
response = es.search(index="索引名", body=query)


# 构建查询
delete_query = {
	"query": {
		"bool": {
			"should": [
				{
					"regexp": {
						# 匹配 字段1 中包含4个或更多连续问号
						"字段名1.keyword": ".*\\?{4,}.*"
					}
				},
				{
					"regexp": {
						# 匹配 字段2 中包含4个或更多连续问号
						"字段名2.keyword": ".*\\?{4,}.*"
					}
				}
			],
			"minimum_should_match": 1  # 至少满足一个条件
		}
	}
}
# 执行删除查询
response = es.delete_by_query(index="索引名", body=delete_query)

编辑:

阅读量:111

url链接:https://www.qozr.com/cms_elasticsearch-chang-yong-cha-xun.html

Tag标签: Elasticsearch , es , kibana

更多新闻

Copyright © 千欧中软 版权所有 www.qozr.com seo | 网站建设 [渝ICP备15005074号] 渝公网安备50011802011077 | sitemap