Elastic Search 安装使用

44 阅读1分钟

1.安装

官方下载地址:www.elastic.co/cn/download…

解压文件,然后创建一个es 用户,给用户文件权限

chown -R es /opt/elasticsearch-9.2.2

修改配置文件,添加ES_JAVA_HOME

vim /etc/profile

export ES_JAVA_HOME="/opt/elasticsearch-9.2.2/jdk"

souce /etc/profile

切换用户

su es

启动es

./bin/elasticsearch -d

//设置密码 用户默认是:elastic

/opt/elasticsearch-9.2.2/bin/elasticsearch-reset-password -u elastic -i

浏览器可以使用插件 Multi Elasticsearch Heads,添加地址,测试连接

2.使用

2.1 创建索引

text和keyword的区别

textkeyword
分词
存储多个token字符串
模糊搜索支持不支持
排序不支持支持
聚合不支持支持
CreateIndexRequest request = CreateIndexRequest.of(c -> c .index("users") // 索引名称 
    .mappings(m -> m .properties("name", p -> p.text(t -> t)) //text类型 
    .properties("age", p -> p.integer(i -> i)) //数字类型 
    .properties("email", p -> p.keyword(k -> k)) // keyword类型 ) ); 
CreateIndexResponse response = client.indices().create(request);

2.2 增加

IndexResponse response = client.index(i -> i .index("users") .id("1") 
    .document(Map.of( "name", "张三", "age", 18, "email", "zhangsan@xxx.com" )) );

2.3 更新

UpdateResponse<Map> updateResponse = client.update(u -> u 
    .index("users") 
    .id("1") .doc(Map.of("age", 29)), Map.class );

2.4 删除

DeleteResponse response = client.delete(d -> d .index("users") .id("1") );

2.5 查询

条件查询
SearchResponse<Map> search = client.search(s -> s 
    .index("users") 
    .query(q -> q 
    .match(m -> m .field("name") .query("张三") ) ), Map.class );
range 范围查询
SearchResponse<Map> rangeSearch = client.search(s -> s 
    .index("users") 
    .from(0).size(10) 
    .query(q -> q 
    .range(r -> r .field("age") .gte(JsonData.of(20)) .lte(JsonData.of(30)) ) ),
    Map.class );
bool 多条件查询

must ==> and

must_not ==> 都不满足

should ==> or

filter ==> 满足条件

match ==> 全文索引

SearchResponse<Map> boolSearch = client.search(s -> s 
    .index("users") 
    .query(q -> q 
    .bool(b -> b 
    .must(m -> m.match(ma -> ma.field("name").query("张三"))) 
    .filter(f -> f.range(r -> r.field("age").gte(20))) ) ), Map.class );