获取JSON的格式的两种方式
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.51</version> </dependency> // 添加文档数据,数据格式为 JSON 格式 request.source(JSON.toJSONString(user), XContentType.JSON);
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</version> </dependency> ObjectMapper objectMapper = new ObjectMapper(); String valueAsString = objectMapper.writeValueAsString(user); request.source(valueAsString, XContentType.JSON);
2.索引库操作
索引库就类似数据库表,mapping映射就类似表的结构。
我们要向es中存储数据,必须先创建“库”和“表”。
2.1.mapping映射属性
mapping是对索引库中文档的约束,常见的mapping属性包括:
-
type:字段数据类型,常见的简单类型有:
-
字符串:text(可分词的文本)、keyword(精确值,例如:品牌、国家、ip地址)
-
数值:long、integer、short、byte、double、float、
-
布尔:boolean
-
日期:date
-
对象:object
-
-
index:是否创建索引,默认为true
-
analyzer:使用哪种分词器
-
properties:该字段的子字段
例如下面的json文档:
{ "age": 21, "weight": 52.1, "isMarried": false, "info": "黑马程序员Java讲师", "email": "zy@itcast.cn", "score": [99.1, 99.5, 98.9], "name": { "firstName": "云", "lastName": "赵" } }
对应的每个字段映射(mapping):
-
age:类型为 integer;参与搜索,因此需要index为true;无需分词器
-
weight:类型为float;参与搜索,因此需要index为true;无需分词器
-
isMarried:类型为boolean;参与搜索,因此需要index为true;无需分词器
-
info:类型为字符串,需要分词,因此是text;参与搜索,因此需要index为true;分词器可以用ik_smart
-
email:类型为字符串,但是不需要分词,因此是keyword;不参与搜索,因此需要index为false;无需分词器
-
score:虽然是数组,但是我们只看元素的类型,类型为float;参与搜索,因此需要index为true;无需分词器
-
name:类型为object,需要定义多个子属性
-
name.firstName;类型为字符串,但是不需要分词,因此是keyword;参与搜索,因此需要index为true;无需分词器
-
name.lastName;类型为字符串,但是不需要分词,因此是keyword;参与搜索,因此需要index为true;无需分词器
-
2.2.索引库的CRUD
这里我们统一使用Kibana编写DSL的方式来演示。
2.2.1.创建索引库和映射
基本语法:
-
请求方式:PUT
-
请求路径:/索引库名,可以自定义
-
请求参数:mapping映射
格式:
PUT /索引库名称 { "mappings": { "properties": { "字段名":{ "type": "text", "analyzer": "ik_smart" }, "字段名2":{ "type": "keyword", "index": "false" }, "字段名3":{ "properties": { "子字段": { "type": "keyword" } } }, // ...略 } } }
示例:
PUT /heima { "mappings": { "properties": { "info":{ "type": "text", "analyzer": "ik_smart" }, "email":{ "type": "keyword", "index": "falsae" }, "name":{ "properties": { "firstName": { "type": "keyword" } } }, // ... 略 } } }
2.2.2.查询索引库
基本语法:
-
请求方式:GET
-
请求路径:/索引库名
-
请求参数:无
格式:
GET /索引库名
2.2.3.修改索引库
倒排索引结构虽然不复杂,但是一旦数据结构改变(比如改变了分词器),就需要重新创建倒排索引,这简直是灾难。因此索引库一旦创建,无法修改mapping。
虽然无法修改mapping中已有的字段,但是却允许添加新的字段到mapping中,因为不会对倒排索引产生影响。
语法说明:
PUT /索引库名/_mapping { "properties": { "新字段名":{ "type": "integer" } } }
2.2.4.删除索引库
语法:
-
请求方式:DELETE
-
请求路径:/索引库名
-
请求参数:无
格式:
DELETE /索引库名
在kibana中测试:
2.2.5.总结
索引库操作有哪些?
-
创建索引库:PUT /索引库名
-
查询索引库:GET /索引库名
-
删除索引库:DELETE /索引库名
-
添加字段:PUT /索引库名/_mapping
3.文档操作
3.1.新增文档
语法:
POST /索引库名/_doc/文档id { "字段1": "值1", "字段2": "值2", "字段3": { "子属性1": "值3", "子属性2": "值4" }, // ... }
示例:
POST /heima/_doc/1 { "info": "黑马程序员Java讲师", "email": "zy@itcast.cn", "name": { "firstName": "云", "lastName": "赵" } }
3.2.查询文档
根据rest风格,新增是post,查询应该是get,不过查询一般都需要条件,这里我们把文档id带上。
语法:
GET /{索引库名称}/_doc/{id}
通过kibana查看数据:
GET /heima/_doc/1
3.3.删除文档
删除使用DELETE请求,同样,需要根据id进行删除:
语法:
DELETE /{索引库名}/_doc/id值
示例:
# 根据id删除数据 DELETE /heima/_doc/1
3.4.修改文档
修改有两种方式:
-
全量修改:直接覆盖原来的文档
-
增量修改:修改文档中的部分字段
3.4.1.全量修改
全量修改是覆盖原来的文档,其本质是:
-
根据指定的id删除文档
-
新增一个相同id的文档
注意:如果根据id删除时,id不存在,第二步的新增也会执行,也就从修改变成了新增操作了。
语法:
PUT /{索引库名}/_doc/文档id { "字段1": "值1", "字段2": "值2", // ... 略 }
示例:
PUT /heima/_doc/1 { "info": "黑马程序员高级Java讲师", "email": "zy@itcast.cn", "name": { "firstName": "云", "lastName": "赵" } }
3.4.2.增量修改
增量修改是只修改指定id匹配的文档中的部分字段。
语法:
POST /{索引库名}/_update/文档id { "doc": { "字段名": "新的值", } }
示例:
POST /heima/_update/1 { "doc": { "email": "ZhaoYun@itcast.cn" } }
3.5.总结
文档操作有哪些?
-
创建文档:POST /{索引库名}/_doc/文档id { json文档 }
-
查询文档:GET /{索引库名}/_doc/文档id
-
删除文档:DELETE /{索引库名}/_doc/文档id
-
修改文档:
-
全量修改:PUT /{索引库名}/_doc/文档id { json文档 }
-
增量修改:POST /{索引库名}/_update/文档id { "doc": {字段}}
-
1.DSL查询文档
elasticsearch的查询依然是基于JSON风格的DSL来实现的。
1.1.DSL查询分类
Elasticsearch提供了基于JSON的DSL(Domain Specific Language)来定义查询。常见的查询类型包括:
-
查询所有:查询出所有数据,一般测试用。例如:match_all
-
全文检索(full text)查询:利用分词器对用户输入内容分词,然后去倒排索引库中匹配。例如:
-
match_query
-
multi_match_query
-
-
精确查询:根据精确词条值查找数据,一般是查找keyword、数值、日期、boolean等类型字段。例如:
-
ids
-
range
-
term
-
-
地理(geo)查询:根据经纬度查询。例如:
-
geo_distance
-
geo_bounding_box
-
-
复合(compound)查询:复合查询可以将上述各种查询条件组合起来,合并查询条件。例如:
-
bool
-
function_score
-
查询的语法基本一致:
GET /indexName/_search { "query": { "查询类型": { "查询条件": "条件值" } } }
我们以查询所有为例,其中:
-
查询类型为match_all
-
没有查询条件
// 查询所有 GET /indexName/_search { "query": { "match_all": { } } }
其它查询无非就是查询类型、查询条件的变化。
1.2.4.总结
match和multi_match的区别是什么?
-
match:根据一个字段查询
-
multi_match:根据多个字段查询,参与查询字段越多,查询性能越差
1.3.精准查询
精确查询一般是查找keyword、数值、日期、boolean等类型字段。所以不会对搜索条件分词。常见的有:
-
term:根据词条精确值查询
-
range:根据值的范围查询
1.3.3.总结
精确查询常见的有哪些?
-
term查询:根据词条精确匹配,一般搜索keyword类型、数值类型、布尔类型、日期类型字段
-
range查询:根据数值范围查询,可以是数值、日期的范围
查询某个字段
GET /ldfxpt3/_search { "query": { "match_all": { } }, "_source": ["gateName","passName"] }
查询分页排序
GET /ldfxpt3/_search { "query": { "match_all": { } }, "from": 0, "size": 2, "_source": ["gateName","passName","passTime"], "sort":{ "passTime":{ "order":"desc" } } }
bool的must查询,相当于and
GET /shopping/_search { "query": { "bool": { "must": [ { "match": { "category": "小米" } } ] } } }
bool的should查询,相当于or
精确查询常见的有哪些?
-
term查询:根据词条精确匹配,一般搜索keyword类型、数值类型、布尔类型、日期类型字段
-
range查询:根据数值范围查询,可以是数值、日期的范围
GET /ldfxpt3/_search { "query": { "bool": { "should": [ { "match": { "gateName": "公交集团" } }, { "match": { "gateName": "KFC肯德基" } } ], "filter": [ { "term": { "passTime": "2022-10-14 10:35:38" } } ] } }, "from": 0, "size": 20 }
match_phrase全文检索查询,高亮显示查询的字段
GET /ldfxpt3/_search { "query": { "match_phrase": { "gateName": "公交集团" } }, "highlight": { "fields": { "gateName": { } } } }
聚合查询
GET /ldfxpt3/_search { "size": 0, "aggs": { "count":{ "cardinality": { "field": "gateName" } }, "gateName_group": { "terms": { "field": "gateName", "order": { "_count": "asc" } } } } }
新建,查询,修改,删除 索引
//新建索引 PUT /user3 { "mappings": { "properties": { "age":{ "type": "text", "index": true }, "name":{ "type": "text", "index": true }, "sex":{ "type": "keyword", "index": true }, "tel":{ "type": "keyword", "index": false } } } } //查询索引 GET /user3 //修改索引,添加新字段,不能修改已有的字段信息 PUT /user3/_mapping { "properties": { "passName":{ "type": "text", "index": true } } } //删除索引 DELETE /user3
新建文档和查询操作
POST /user3/_doc/1001 { "age": 12, "name": "张三", "passName": "星星快递", "sex": "男的", "tel": 11111 } GET /user3/_doc/1001 GET /user3/_search { "query": { "match": { "tel": "11111" } } }
API操作 索引
创建索引
package com.example.testes.index; import java.io.IOException; import org.apache.http.HttpHost; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; public class CreateIndex { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); // 创建索引 - 请求对象 CreateIndexRequest request = new CreateIndexRequest("user2"); // 发送请求,获取响应 CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); boolean acknowledged = response.isAcknowledged(); // 响应状态 System.out.println("操作状态 = " + acknowledged); System.out.println(client); // 关闭客户端连接 client.close(); } }
查询索引
package com.example.testes.index; import org.apache.http.HttpHost; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.indices.GetIndexResponse; import java.io.IOException; public class SearchIndex { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); //查询索引 - 请求对象 GetIndexRequest request = new GetIndexRequest("user2"); // 发送请求,获取响应 GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT); System.out.println("aliases:"+response.getAliases()); System.out.println("mappings:"+response.getMappings()); System.out.println("settings:"+response.getSettings()); // 关闭客户端连接 client.close(); } }
删除索引
package com.example.testes.index; import org.apache.http.HttpHost; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.indices.GetIndexResponse; import java.io.IOException; public class DeleteIndex { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); // 删除索引 - 请求对象 DeleteIndexRequest request = new DeleteIndexRequest("user2"); // 发送请求,获取响应 AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT); // 操作结果 System.out.println("操作结果 : " + response.isAcknowledged()); // 关闭客户端连接 client.close(); } }
API操作 文档
实体类
package com.example.testes.doc; public class User { private int age; private String name; private int tel; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getTel() { return tel; } public void setTel(int tel) { this.tel = tel; } }
文档添加
package com.example.testes.doc; import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpHost; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.indices.GetIndexResponse; import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; public class InsertDoc { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); //新建文档 -- 请求对象 IndexRequest request = new IndexRequest(); //设置索引及唯一性标识 request.index("user2").id("1002"); User user = new User(); user.setAge(23); user.setName("zhang"); user.setTel(1124455444); ObjectMapper objectMapper = new ObjectMapper(); String valueAsString = objectMapper.writeValueAsString(user); request.source(valueAsString, XContentType.JSON); // 添加文档数据,数据格式为 JSON 格式 // request.source(JSON.toJSONString(user), XContentType.JSON); // 添加文档数据,数据格式为 JSON 格式 IndexResponse response = client.index(request, RequestOptions.DEFAULT); // 添加文档数据,数据格式为 JSON 格式 System.out.println(response.getIndex()); System.out.println(response.getResult()); System.out.println(response.getId()); // 关闭客户端连接 client.close(); } }
文档查询
package com.example.testes.doc; import org.apache.http.HttpHost; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; public class GetDoc { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); //新建文档 -- 请求对象 GetRequest request = new GetRequest(); //设置索引及唯一性标识 request.index("user2").id("1001"); // 添加文档数据,数据格式为 JSON 格式 GetResponse response = client.get(request, RequestOptions.DEFAULT); // 添加文档数据,数据格式为 JSON 格式 System.out.println("_index:" + response.getIndex()); System.out.println("_id:" +response.getId()); System.out.println("_type:" + response.getSource()); System.out.println("source:" + response.getSourceAsString()); // 关闭客户端连接 client.close(); } }
文档更新
package com.example.testes.doc; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpHost; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; public class UpdateDoc { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); //新建文档 -- 请求对象 UpdateRequest request = new UpdateRequest(); //设置索引及唯一性标识 request.index("user2").id("1002"); request.doc(XContentType.JSON,"name","王五"); // 添加文档数据,数据格式为 JSON 格式 UpdateResponse response = client.update(request, RequestOptions.DEFAULT); // 添加文档数据,数据格式为 JSON 格式 System.out.println(response.getIndex()); System.out.println(response.getResult()); System.out.println(response.getId()); // 关闭客户端连接 client.close(); } }
文档删除
package com.example.testes.doc; import org.apache.http.HttpHost; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import java.io.IOException; public class DeleteDoc { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); DeleteRequest request = new DeleteRequest(); //设置索引及唯一性标识 request.index("user2").id("1002"); // 添加文档数据,数据格式为 JSON 格式 DeleteResponse response = client.delete(request, RequestOptions.DEFAULT); // 添加文档数据,数据格式为 JSON 格式 System.out.println("_index:" + response.getIndex()); System.out.println("_id:" +response.getId()); System.out.println(response.toString()); // 关闭客户端连接 client.close(); } }
批量添加文档
package com.example.testes.doc; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpHost; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.xcontent.XContentType; import java.io.IOException; public class InsertDoc_Batch { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); BulkRequest bulkRequest = new BulkRequest(); bulkRequest.add(new IndexRequest().index("user2").id("1003").source(XContentType.JSON,"name","dsfdsf","age",12,"tel",25)); bulkRequest.add(new IndexRequest().index("user2").id("1004").source(XContentType.JSON,"name","lisi","age",13,"tel",25)); bulkRequest.add(new IndexRequest().index("user2").id("1005").source(XContentType.JSON,"name","wangwi","age",15,"tel",25)); bulkRequest.add(new IndexRequest().index("user2").id("1006").source(XContentType.JSON,"name","zhangs","age",92,"tel",25)); BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT); System.out.println(response.getTook()); System.out.println(response.getItems()); } }
批量删除文档
package com.example.testes.doc; import org.apache.http.HttpHost; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import java.io.IOException; public class DeleteDoc_Batch { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); BulkRequest request = new BulkRequest(); request.add(new DeleteRequest().index("user2").id("1003")); request.add(new DeleteRequest().index("user2").id("1004")); request.add(new DeleteRequest().index("user2").id("1005")); request.add(new DeleteRequest().index("user2").id("1006")); BulkResponse response = client.bulk(request, RequestOptions.DEFAULT); System.out.println(response.getTook()); System.out.println(response.getItems()); } }
查询全部文档
package com.example.testes.doc; import org.apache.http.HttpHost; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchScrollRequestBuilder; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.io.IOException; public class BatchInsertDoc { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); // 创建搜索请求对象 SearchRequest request = new SearchRequest("user2"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchAllQuery()); request.source(sourceBuilder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 查询匹配 SearchHits hits = response.getHits(); System.out.println("took:" + response.getTook()); System.out.println("timeout:" + response.isTimedOut()); System.out.println("total:" + hits.getTotalHits()); System.out.println("MaxScore:" + hits.getMaxScore()); System.out.println("hits========>>"); for (SearchHit hit : hits) { //输出每条查询的结果信息 System.out.println(hit.getSourceAsString()); } System.out.println("<<========"); // 关闭客户端连接 client.close(); } }
条件查询,分页查询,排序,输入指定的字段
package com.example.testes.doc; import org.apache.http.HttpHost; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.sort.SortOrder; import java.io.IOException; public class QueryDoc { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); /** * 条件查询 */ /* // 创建搜索请求对象 SearchRequest request = new SearchRequest("user2"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("name","wangwi")); request.source(sourceBuilder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 查询匹配 SearchHits hits = response.getHits(); System.out.println("took:" + response.getTook()); System.out.println("timeout:" + response.isTimedOut()); System.out.println("total:" + hits.getTotalHits()); System.out.println("MaxScore:" + hits.getMaxScore()); System.out.println("hits========>>"); for (SearchHit hit : hits) { //输出每条查询的结果信息 System.out.println(hit.getSourceAsString()); } System.out.println("<<========");*/ --------------------------------------------------------------------------------------------------------- /** * 分页查询 */ /* // 创建搜索请求对象 SearchRequest request = new SearchRequest("user2"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchAllQuery()).from(0).size(2); request.source(sourceBuilder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 查询匹配 SearchHits hits = response.getHits(); System.out.println("took:" + response.getTook()); System.out.println("timeout:" + response.isTimedOut()); System.out.println("total:" + hits.getTotalHits()); System.out.println("MaxScore:" + hits.getMaxScore()); System.out.println("hits========>>"); for (SearchHit hit : hits) { //输出每条查询的结果信息 System.out.println(hit.getSourceAsString()); } System.out.println("<<========"); */ --------------------------------------------------------------------------------------------------------- /** * 查询排序 */ // 创建搜索请求对象 SearchRequest request = new SearchRequest("user2"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); SearchSourceBuilder builder = sourceBuilder.query(QueryBuilders.matchAllQuery()); //只包含这个字段 String[] includes = {"name"}; //去除这个字段 String[] encludes = {}; builder.fetchSource(includes,encludes).sort("age", SortOrder.DESC); request.source(builder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 查询匹配 SearchHits hits = response.getHits(); System.out.println("took:" + response.getTook()); System.out.println("timeout:" + response.isTimedOut()); System.out.println("total:" + hits.getTotalHits()); System.out.println("MaxScore:" + hits.getMaxScore()); System.out.println("hits========>>"); for (SearchHit hit : hits) { //输出每条查询的结果信息 System.out.println(hit.getSourceAsString()); } System.out.println("<<========"); // 关闭客户端连接 client.close(); } }
分组查询,范围查询
public class QueryDoc { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); /** * 组合查询 */ /* // 创建搜索请求对象 SearchRequest request = new SearchRequest("user2"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); // 必须包含 boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30")); // 一定不含 boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name","wangwi")); // 可能包含 boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男")); sourceBuilder.query(boolQueryBuilder); request.source(sourceBuilder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 查询匹配 SearchHits hits = response.getHits(); System.out.println("took:" + response.getTook()); System.out.println("timeout:" + response.isTimedOut()); System.out.println("total:" + hits.getTotalHits()); System.out.println("MaxScore:" + hits.getMaxScore()); System.out.println("hits========>>"); for (SearchHit hit : hits) { //输出每条查询的结果信息 System.out.println(hit.getSourceAsString()); } System.out.println("<<========");*/ --------------------------------------------------------------------------------------------------------- public class QueryDoc { public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); /** * 范围查询 */ // 创建搜索请求对象 SearchRequest request = new SearchRequest("user2"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); RangeQueryBuilder builder = QueryBuilders.rangeQuery("age"); builder.gte(15).lte(25); sourceBuilder.query(builder); request.source(sourceBuilder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 查询匹配 SearchHits hits = response.getHits(); System.out.println("took:" + response.getTook()); System.out.println("timeout:" + response.isTimedOut()); System.out.println("total:" + hits.getTotalHits()); System.out.println("MaxScore:" + hits.getMaxScore()); System.out.println("hits========>>"); for (SearchHit hit : hits) { //输出每条查询的结果信息 System.out.println(hit.getSourceAsString()); } System.out.println("<<========"); // 关闭客户端连接 client.close(); }
模糊查询,高亮查询
public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); /** * 模糊查询 */ /*// 创建搜索请求对象 SearchRequest request = new SearchRequest("user2"); // 构建查询的请求体 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "zhang").fuzziness(Fuzziness.TWO); sourceBuilder.query(fuzzyQueryBuilder); request.source(sourceBuilder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 查询匹配 SearchHits hits = response.getHits(); System.out.println("took:" + response.getTook()); System.out.println("timeout:" + response.isTimedOut()); System.out.println("total:" + hits.getTotalHits()); System.out.println("MaxScore:" + hits.getMaxScore()); System.out.println("hits========>>"); for (SearchHit hit : hits) { //输出每条查询的结果信息 System.out.println(hit.getSourceAsString()); } System.out.println("<<========"); // 关闭客户端连接 client.close(); }*/ --------------------------------------------------------------------------------------------------------- public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); /** * 高亮显示 */ // 高亮查询 SearchRequest request = new SearchRequest().indices("user2"); //2.创建查询请求体构建器 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //构建查询方式:高亮查询 TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name","zhangs"); //设置查询方式 sourceBuilder.query(termsQueryBuilder); //构建高亮字段 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.preTags("<font color='red'>");//设置标签前缀 highlightBuilder.postTags("</font>");//设置标签后缀 highlightBuilder.field("name");//设置高亮字段 //设置高亮构建对象 sourceBuilder.highlighter(highlightBuilder); //设置请求体 request.source(sourceBuilder); //3.客户端发送请求,获取响应对象 SearchResponse response = client.search(request, RequestOptions.DEFAULT); //4.打印响应结果 SearchHits hits = response.getHits(); System.out.println("took::"+response.getTook()); System.out.println("time_out::"+response.isTimedOut()); System.out.println("total::"+hits.getTotalHits()); System.out.println("max_score::"+hits.getMaxScore()); System.out.println("hits::::>>"); for (SearchHit hit : hits) { String sourceAsString = hit.getSourceAsString(); System.out.println(sourceAsString); //打印高亮结果 Map<String, HighlightField> highlightFields = hit.getHighlightFields(); System.out.println(highlightFields); } System.out.println("<<::::"); // 关闭客户端连接 client.close(); }
最大值查询,分组查询
public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); /** * 最大值查询 */ /* SearchRequest request = new SearchRequest().indices("user2"); //2.创建查询请求体构建器 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //构建查询方式: sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age")); //设置请求体 request.source(sourceBuilder); //3.客户端发送请求,获取响应对象 SearchResponse response = client.search(request, RequestOptions.DEFAULT); //4.打印响应结果 SearchHits hits = response.getHits(); System.out.println("took::"+response.getTook()); System.out.println("time_out::"+response.isTimedOut()); System.out.println("total::"+hits.getTotalHits()); System.out.println("max_score::"+hits.getMaxScore()); System.out.println("hits::::>>"); for (SearchHit hit : hits) { String sourceAsString = hit.getSourceAsString(); System.out.println(sourceAsString); } System.out.println("<<::::"); // 关闭客户端连接 client.close(); }*/ --------------------------------------------------------------------------------------------------------- public static void main(String[] args) throws IOException { // 创建客户端对象 RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.XXXX", 9200, "http"))); /** * 分组查询 */ SearchRequest request = new SearchRequest().indices("user2"); //2.创建查询请求体构建器 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); //构建查询方式: sourceBuilder.aggregation(AggregationBuilders.terms("age_group").field("age")); //设置请求体 request.source(sourceBuilder); //3.客户端发送请求,获取响应对象 SearchResponse response = client.search(request, RequestOptions.DEFAULT); //4.打印响应结果 SearchHits hits = response.getHits(); System.out.println(response); // 关闭客户端连接 client.close(); }