ElasticSearch 使用指南

本文详细介绍了如何在Elasticsearch中进行特殊查询,包括处理空字符串、空数组,以及更新文档时指定返回字段,并展示了分页和排序的实战示例。涵盖了布尔查询、范围查询、多字段查询和更新操作的高级技巧。

ES【查询】参考文章:https://blog.youkuaiyun.com/lazyboy2/article/details/125122833

查询

单条查询

// /_index/_search
POST  /free_study_stu_all_info_*/_search
{
  "query": {
    "match": {
      "orderNo": "1_1657873553700"
    }
  }
}

多条查询

// 多条查询,相当于sql中的in查询
GET  /free_study_stu_all_info_*/_search
{
  "query": {
    "terms": { // 多条精确匹配
      "orderNo": [
        "11_1603955970027",
        "11_1603957926122"
      ]
    }
  }
}

范围查询

// 范围查询,相当于sql的>,<,!=
GET  /free_study_stu_all_info_*/_search
{
  "query": {
    "range": {
      "createTime": {
        "gte": "2022-11-15 00:00:00" // 大于等于
        "gt": "2022-11-15 00:00:00" // 大于
      }
    }
  }
}

多个字段查询

// 多个字段查询
GET /{索引名}/_search
{
  "query": {
    "bool": { // bool查询
      "must": [], // must条件,类似SQL中的and, 代表必须匹配条件
      "must_not": [], // must_not条件,跟must相反,必须不匹配条件
      "should": [] // should条件,类似SQL中or, 代表匹配其中一个条件
    }
  }
}

示例

GET  /free_study_stu_all_info_*/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "orderNo": "1_1666265202972"
          }
        },
        {
          "term": {
            "brandId": 1
          }
        }
      ]
    }
  }
}

综合示例

GET /order_v2/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "order_no": "2020031312091209991"
                }
              },
              {
                "range": {
                  "shop_id": {
                    "gte": 10,
                    "lte": 200
                  }
                }
              }
            ]
          }
        },
        {
          "terms": {
            "tag": [
              1,
              2,
              3,
              4,
              5,
              12
            ]
          }
        }
      ]
    }
  }
}

特殊查询(字符串为空或空数组)

字符串不为空

{
  "query": {
    "wildcard": {
      "entUserId": { // 字段名称
        "value": "*"
      }
    }
  }
}

字符串为空

{
  "query": {
    "bool": {
      "must_not": [
        {
          "wildcard": {
            "entUserId": {
              "value": "*"
            }
          }
        }
      ]
    }
  }
}

对象数组为空

{
  "query": {
    "nested": {
      "path": "studentRoundInfos",
      "query": {
        "bool": {
          "must": {
            "exists": {
              "field": "studentRoundInfos"
            }
          }
        }
      }
    }
  }
}

对象数组不为空

{
    "query": {
        "bool": {
            "must_not": [{
                "nested": {
                    "path": "studentRoundInfos",
                    "query": {
                        "exists": {
                            "field": "studentRoundInfos"
                        }
                    }
                }
            }]
        }
    }
}

更新

// 按条件修改 /_index/_type/_id/_update
POST /free_study_stu_all_info_test2/free_study_stu_all_info_test2/3974830/_update
{
  "doc": {
    "userTagList":["A"]
  }
}

结果

// 返回结果
{
  "_index" : "free_study_stu_all_info_test2",
  "_type" : "free_study_stu_all_info_test2",
  "_id" : "590048",
  "_version" : 3,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 3418842,
  "_primary_term" : 4
}

指定返回字段

在这里插入图片描述

分页

在这里插入图片描述

排序

GET /order_v2/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "user.id": { // 嵌套json对象,使用 点 连接字段名即可
        "order": "desc"
      }
    }
  ]
}

### Elasticsearch 使用教程及官方文档指南 Elasticsearch 是一个分布式、开源的搜索和分析引擎,基于 Apache Lucene 构建。它能够快速地存储、搜索和分析大规模数据[^1]。以下是关于 Elasticsearch使用指南、官方文档、配置以及示例的详细介绍。 #### 1. 启动 Elasticsearch 在安装完成后,可以通过命令行进入 Elasticsearch 安装目录的 `bin` 文件夹,并执行以下命令来启动 Elasticsearch 服务: ```bash ./elasticsearch ``` 此命令将启动 Elasticsearch 服务,默认监听端口为 `9200`[^1]。 #### 2. 配置 Elasticsearch Elasticsearch 的主要配置文件位于 `config/elasticsearch.yml` 中。常见的配置包括集群名称、节点名称、网络绑定地址等。例如: ```yaml cluster.name: my-cluster node.name: node-1 network.host: 0.0.0.0 http.port: 9200 ``` 这些配置项可以满足大多数基础需求[^4]。 #### 3. 插件安装(以 IK 分词器为例) 为了增强 Elasticsearch 的功能,可以安装插件。例如,IK 分词器是一个常用的中文分词插件。下载并安装 IK 分词器的方法如下: ```bash wget https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.4.0/elasticsearch-analysis-ik-7.4.0.zip unzip elasticsearch-analysis-ik-7.4.0.zip -d plugins/ ``` 完成安装后,重启 Elasticsearch 服务即可生效[^2]。 #### 4. Java 项目连接 Elasticsearch 示例 以下是一个简单的 Java 代码示例,展示如何通过 TransportClient 连接到 Elasticsearch 并执行查询操作: ```java package com.edu.elasticSearch; import java.net.InetAddress; import java.net.UnknownHostException; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.transport.client.PreBuiltTransportClient; public class ESTest { public static void main(String[] args) throws UnknownHostException { Settings settings = Settings.builder() .put("cluster.name", "my-cluster") .build(); TransportClient client = new PreBuiltTransportClient(settings) .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); GetResponse response = client.prepareGet("index_name", "type_name", "id").get(); System.out.println(response.getSourceAsString()); client.close(); } } ``` 上述代码展示了如何创建 TransportClient 并执行获取文档的操作[^3]。 #### 5. Spring Boot 集成 Elasticsearch 示例 在 Spring Boot 项目中集成 Elasticsearch 可以简化开发流程。以下是一个简单的集成示例: 1. 添加依赖到 `pom.xml` 文件: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置 `application.yml` 文件: ```yaml spring: elasticsearch: rest: uris: http://localhost:9200 ``` 3. 创建实体类和 Repository 接口: ```java @Entity public class User { @Id private String id; private String name; private int age; // getters and setters } public interface UserRepository extends ElasticsearchRepository<User, String> { } ``` 4. 使用 Service 层进行 CRUD 操作: ```java @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> findAllUsers() { return userRepository.findAll(); } } ``` 以上代码展示了如何在 Spring Boot 中配置和使用 Elasticsearch[^4]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值