MST

星途 面试题库

面试题:ElasticSearch中如何使用任务API实现基于特定条件的查询和删除

假设在ElasticSearch中有一个索引存储了用户信息,包括姓名、年龄、地址等字段。现在要求你使用任务API,编写查询语句找出年龄大于30岁且地址在某个城市的用户记录,并展示如何使用任务API删除这些查询出来的记录。请写出具体的API请求及参数设置。
28.9万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试
  1. 查询年龄大于30岁且地址在某个城市的用户记录
    • 假设索引名为user_index,地址字段为address,城市为Shanghai,查询语句如下:
    POST user_index/_search
    {
        "query": {
            "bool": {
                "must": [
                    {
                        "range": {
                            "age": {
                                "gt": 30
                            }
                        }
                    },
                    {
                        "match": {
                            "address": "Shanghai"
                        }
                    }
                ]
            }
        }
    }
    
  2. 使用任务API删除这些查询出来的记录
    • Elasticsearch 7.1及以上版本,可以使用delete_by_query API结合任务API。首先发起delete_by_query请求:
    POST user_index/_delete_by_query?conflicts=proceed&refresh=true
    {
        "query": {
            "bool": {
                "must": [
                    {
                        "range": {
                            "age": {
                                "gt": 30
                            }
                        }
                    },
                    {
                        "match": {
                            "address": "Shanghai"
                        }
                    }
                ]
            }
        }
    }
    
    • conflicts=proceed参数表示在删除过程中遇到版本冲突时继续执行。refresh=true表示操作完成后立即刷新索引,使更改可见。
    • 这个delete_by_query请求会返回一个任务ID,例如:
    {
        "task": "AV4917R8m927J8G1K99J:354520"
    }
    
    • 可以使用任务API获取任务状态,例如:
    GET _tasks/AV4917R8m927J8G1K99J:354520
    
    • 这个请求会返回任务的详细状态信息,包括任务是否完成、进度等。