Java elasticSearch-api的具體操作步驟講解
使用步驟
1.環境準備
用的是windows版,自行下載
鏈接: 下載地址
2.針對索引操作
這裡是kibana上操作的(也可以用postman操作):
#創建索引,指定文檔id PUT /test1/type1/1 { "name":"張三", "age":30 } #創建索引規則(類似數據庫建表) PUT /test2 { "mappings": { "properties": { "name":{ "type":"text" }, "age":{ "type": "integer" }, "birthday":{ "type": "date" } } } } #獲取索引的信息,properties類型 GET test2 #創建索引,properties不指定類型會有默認類型 #也可以用作修改,但是必須寫上全部字段,不然會丟失未寫字段 PUT /test3/_doc/1 { "name":"張三", "age":30, "birth":"1991-06-23" } GET test3 #查看es健康狀態 GET _cat/health #查看所有索引狀態 GET _cat/indices?v #修改 POST /test3/_doc/1/_update { "doc":{ "name":"李四" } }
3.針對doc操作(增刪改)
代碼如下(示例):
#新增索引,並添加doc POST /chen/user/1 { "name":"張三", "age":11, "desc":"一頓操作猛如虎,一看工資2500", "tags":["技術宅","溫暖","直男"] } POST /chen/user/2 { "name":"李四", "age":12, "desc":"憨批", "tags":["渣男","旅遊","交友"] } POST /chen/user/3 { "name":"王五", "age":13, "desc":"瓜慫", "tags":["靚女","旅遊","美食"] } POST /chen/user/4 { "name":"劉六", "age":14, "desc":"鍋盔", "tags":["衰仔","旅遊","美食"] } #獲取數據 GET chen/user/1 #更新數據 POST chen/user/1/_update { "doc":{ "name":"更新" } } #刪除 DELETE chen/user/1 #條件查詢,匹配度越高,_score(分值)越高 GET chen/user/_search?q=name:李 GET chen/user/_search?q=name:李四 #等價於上面 GET chen/user/_search { "query": { "match": { "name": "李四" } } }
4.針對doc操作(查)
查詢1(示例):
#_source結果過濾(指定需要字段結果集) #sort排序 #from-size分頁(類似limit ) #註意:這個查詢是不可以些多個字段的(我試過瞭) GET chen/user/_search { "query": { "match": { "name": "李四" } }, "_source": ["name","age"], "sort": [ { "age": { "order": "asc" } } ], "from":0, "size":1 } #多條件精確查詢 #以下都是bool的二級屬性 #must:必須 #should,滿足任意條件 #must_not,表示不滿足 GET chen/user/_search { "query": { "bool": { "must": [ {"match": { "name": "李四" }}, {"match": { "age": 11 }} ] } } } #過濾.註意filter是bool(多條件)的二級屬性 GET chen/user/_search { "query": { "bool": { "must": [ {"match": { "name": "李四" }} ], "filter": { "range": { "age": { "gte": 10, "lte": 20 } } } } } } #分詞器依然有效 #多個條件空格隔開就行,隻要滿足其中一個,就會被逮到 GET chen/user/_search { "query": { "match": { "tags": "男 技術" } } } #精確查詢,結果隻能為1,多條直接不顯示 GET chen/user/_search { "query": { "term": { "name": "李四" } } }
查詢2(示例):
#新建索引 PUT test4 { "mappings": { "properties": { "name":{ "type": "text" }, "desc":{ "type": "keyword" } } } } #插入數據 PUT test4/_doc/1 { "name":"張三name", "desc":"張三desc" } PUT test4/_doc/2 { "name":"張三name2", "desc":"張三desc2" } #分詞器查詢(並不是查詢索引裡的數據,而是將text的內容用分詞器拆分的結果) GET _analyze { "analyzer": "keyword", "text": ["張三name"] } GET _analyze { "analyzer": "standard", "text": "張三name" } GET test4/_search { "query": { "term": { "name": "張" } } } #==keyword不會被分詞器解析== GET test4/_search { "query": { "term": { "desc": "張三desc" } } }
查詢3(示例):
PUT test4/_doc/3 { "t1":"22", "t2":"2020-4-6" } PUT test4/_doc/4 { "t1":"33", "t2":"2020-4-7" } #精確查詢多個值 GET test4/_search { "query": { "bool": { "should": [ { "term": { "t1": "22" } }, { "term": { "t1": "33" } } ] } } } #highlight:高亮 #pre_tags,post_tags:自定義高亮條件,前綴後綴 GET chen/user/_search { "query": { "match": { "name": "李四" } }, "highlight": { "pre_tags": "<p class='key' style='color:red'", "post_tags": "</p>", "fields": { "name":{} } } }
5.java-api
索引操作:
public class ES_Index { private static final String HOST_NAME = "localhost"; private static final Integer PORT = 9200; private static RestHighLevelClient client; //創建ES客戶端 static { RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(HOST_NAME, PORT)); client = new RestHighLevelClient(restClientBuilder); } //關閉ES客戶端 public void close() { if (null != client) { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } //創建索引 public void addIndex() throws IOException { //創建索引 CreateIndexRequest request = new CreateIndexRequest("chen"); CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); //響應狀態 System.out.println("索引創建操作: " + response.isAcknowledged()); } //查詢索引 public void selectIndex() throws IOException { GetIndexRequest request = new GetIndexRequest("chen"); GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT); System.out.println("索引查詢操作: " +response.getAliases()); System.out.println("索引查詢操作: " +response.getMappings()); System.out.println("索引查詢操作: " +response.getSettings()); } //刪除索引 public void deleteIndex() throws IOException { DeleteIndexRequest request = new DeleteIndexRequest("chen"); AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT); System.out.println("索引刪除操作: "+response.isAcknowledged()); } public static void main(String[] args) throws IOException { ES_Index index=new ES_Index(); //index.addIndex(); //index.selectIndex(); index.deleteIndex(); index.close(); } }
文檔操作:
public class ES_Doc { private static final String HOST_NAME = "localhost"; private static final Integer PORT = 9200; private static RestHighLevelClient client; //創建ES客戶端 static { RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(HOST_NAME, PORT)); client = new RestHighLevelClient(restClientBuilder); } //關閉ES客戶端 public void close() { if (null != client) { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } //插入數據 public void addDoc() throws IOException { IndexRequest request = new IndexRequest(); User user = new User("張三", "男", 18); //向es插入數據,必須將數據轉換為json格式 String userJson = new ObjectMapper().writeValueAsString(user); request.index("user").id("1001").source(userJson, XContentType.JSON); IndexResponse response = client.index(request, RequestOptions.DEFAULT); System.out.println("文檔創建操作: " + response.getResult()); } //修改數據(局部修改) public void updateDoc() throws IOException { UpdateRequest request = new UpdateRequest(); request.index("user").id("1001").doc(XContentType.JSON, "sex", "女"); UpdateResponse response = client.update(request, RequestOptions.DEFAULT); System.out.println("文檔修改操作: " + response.getResult()); } //獲取數據 public void getDoc() throws IOException { GetRequest request = new GetRequest(); request.index("user").id("1001"); GetResponse response = client.get(request, RequestOptions.DEFAULT); User user = new ObjectMapper().readValue(response.getSourceAsString(), User.class); System.out.println("文檔獲取操作: " + user); } //刪除數據 public void deleteDoc() throws IOException { DeleteRequest request = new DeleteRequest(); request.index("user").id("1001"); DeleteResponse response = client.delete(request, RequestOptions.DEFAULT); System.out.println("文檔刪除操作: " + response.getResult()); } //批量插入數據 public void addBatch() throws IOException { BulkRequest request = new BulkRequest(); request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "張三", "sex", "男", "age", 10)); request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "李四", "sex", "男", "age", 20)); request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "王五", "sex", "女", "age", 30)); request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "趙六", "sex", "男", "age", 40)); request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "孫七", "sex", "女", "age", 50)); BulkResponse response = client.bulk(request, RequestOptions.DEFAULT); System.out.println("文檔批量新增操作: " + response.getTook()); System.out.println("文檔批量新增操作: " + !response.hasFailures());//是否失敗 } //批量刪除數據 public void deleteBatch() throws IOException { BulkRequest request = new BulkRequest(); request.add(new DeleteRequest().index("user").id("1001")); request.add(new DeleteRequest().index("user").id("1002")); request.add(new DeleteRequest().index("user").id("1003")); request.add(new DeleteRequest().index("user").id("1004")); request.add(new DeleteRequest().index("user").id("1005")); BulkResponse response = client.bulk(request, RequestOptions.DEFAULT); System.out.println("文檔批量刪除操作: " + response.getTook()); System.out.println("文檔批量刪除操作: " + !response.hasFailures());//是否失敗 } //查詢(重點) public void searchDoc() throws IOException { SearchRequest request = new SearchRequest(); request.indices("user"); //1.查詢索引中的全部數據 //request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery())); //2.查詢年齡為30的數據 //request.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age", 30))); //3.分頁查詢,當前第0頁,每頁兩條 //request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).from(0).size(2)); //4.排序,倒序 //request.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).sort("age", SortOrder.DESC)); //5.過濾字段(排除和包含,也可以是數組) //request.source(new SearchSourceBuilder().fetchSource("name", null)); //6.組合查詢 //BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); //6.1 must相當於and //boolQueryBuilder.must(QueryBuilders.matchQuery("age", 30)); //boolQueryBuilder.must(QueryBuilders.matchQuery("sex", "女")); //6.2 should相當於or //boolQueryBuilder.should(QueryBuilders.matchQuery("age", 30)); //boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "女")); //request.source(new SearchSourceBuilder().query(boolQueryBuilder)); //7.范圍查詢 //request.source(new SearchSourceBuilder().query(QueryBuilders.rangeQuery("age").gte(30).lte(40))); //8.模糊查詢Fuzziness.ONE即隻差1個字符 //request.source(new SearchSourceBuilder().query(QueryBuilders.fuzzyQuery("name", "王五").fuzziness(Fuzziness.ONE))); //9.高亮顯示 //SearchSourceBuilder builder = new SearchSourceBuilder().query(QueryBuilders.matchPhraseQuery("name", "張三")); //builder.highlighter(new HighlightBuilder().preTags("<font color='red'>").postTags("</font>").field("name")); //request.source(builder); //10.聚合查詢 //SearchSourceBuilder builder = new SearchSourceBuilder(); //MaxAggregationBuilder aggregationBuilder = AggregationBuilders.max("maxAge").field("age"); //builder.aggregation(aggregationBuilder); //request.source(builder); //11.分組查詢 SearchSourceBuilder builder = new SearchSourceBuilder(); TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("ageGroup").field("age"); builder.aggregation(aggregationBuilder); request.source(builder); SearchResponse response = client.search(request, RequestOptions.DEFAULT); SearchHits hits = response.getHits(); System.out.println("--條數: " + hits.getTotalHits()); System.out.println("--用時: " + response.getTook()); hits.forEach((item)->{ System.out.println("--數據: " + item.getSourceAsString()); }); } public static void main(String[] args) throws IOException { ES_Doc doc = new ES_Doc(); //doc.addDoc(); //doc.updateDoc(); //doc.getDoc(); //doc.deleteDoc(); //doc.addBatch(); //doc.deleteBatch(); doc.searchDoc(); doc.close(); } }
6.spring-data-elasticsearch
實體類: 關鍵在於@Document和@Field註解
shards 代表分片
replicas 代表副本
@Data @NoArgsConstructor @AllArgsConstructor @Document(indexName = "product", shards = 3, replicas = 1) public class Product { @Id private Long id;//商品唯一標識 @Field(type = FieldType.Text) private String title;//商品名稱 @Field(type = FieldType.Keyword) private String category;//分類名稱 @Field(type = FieldType.Double) private Double price;//商品價格 @Field(type = FieldType.Keyword,index = false) private String images;//圖片地址 }
dao層: 這樣就已經可以瞭,類似mybatis-plus的BaseMapper,封裝好瞭一些操作
@Repository public interface ProductDao extends ElasticsearchRepository<Product,Long> { }
yaml :不用怎麼配置,默認就去找localhost:9200
測試 :不知道為啥dao的很多方法都過時瞭,看源碼註釋讓回去用elasticsearchRestTemplate,感覺更繁瑣
@SpringBootTest class ElasticsearchApplicationTests { @Autowired ElasticsearchRestTemplate elasticsearchRestTemplate; @Autowired ProductDao productDao; @Test void createIndex() { //創建索引,系統初始化會自動創建索引 System.out.println("創建索引"); } @Test void deleteIndex() { //創建索引,系統初始化會自動創建索引 boolean flg = elasticsearchRestTemplate.deleteIndex(Product.class); System.out.println("刪除索引 = " + flg); } //新增數據 @Test void addDoc() { Product product = new Product(); product.setId(1001L); product.setTitle("華為手機"); product.setCategory("手機"); product.setPrice(2999.0); product.setImages("www.huawei.com"); productDao.save(product); } //修改 @Test void updateDoc() { Product product = new Product(); product.setId(1001L); product.setTitle("小米手機"); product.setCategory("手機"); product.setPrice(4999.0); product.setImages("www.xiaomi.com"); productDao.save(product); } //根據 id 查詢 @Test void findById() { Product product = productDao.findById(1001L).get(); System.out.println(product); } //查詢所有 @Test void findAll() { Iterable<Product> products = productDao.findAll(); for (Product product : products) { System.out.println(product); } } //刪除 @Test public void delete() { productDao.deleteById(1001L); } //批量新增 @Test public void saveAll() { List<Product> productList = new ArrayList<>(); for (int i = 0; i < 10; i++) { Product product = new Product(); product.setId((long) i); product.setTitle("[" + i + "]小米手機"); product.setCategory("手機"); product.setPrice(1999.0 + i); product.setImages("http://www.atguigu/xm.jpg"); productList.add(product); } productDao.saveAll(productList); } //分頁查詢 @Test void findByPageable() { Sort orders = Sort.by(Sort.Direction.DESC, "id"); Pageable pageable = PageRequest.of(0, 5, orders); Page<Product> products = productDao.findAll(pageable); products.forEach(System.out::println); } /** * term 查詢 * search(termQueryBuilder) 調用搜索方法,參數查詢構建器對象 */ @Test void termQuery() { TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手機"); Iterable<Product> products = productDao.search(termQueryBuilder); products.forEach(System.out::println); } /** * term 查詢加分頁 */ @Test void termQueryByPage() { PageRequest pageRequest = PageRequest.of(0, 5); TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("category", "手機"); Iterable<Product> products = productDao.search(termQueryBuilder, pageRequest); products.forEach(System.out::println); } }
到此這篇關於elasticSearch-api的具體操作步驟講解的文章就介紹到這瞭,更多相關elasticSearch-api詳解內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Elasticsearch查詢之Term Query示例解析
- SpringBoot框架集成ElasticSearch實現過程示例詳解
- springboot中使用ElasticSearch的詳細教程
- SpringBoot+Elasticsearch實現數據搜索的方法詳解
- SpringBoot 整合 Elasticsearch 實現海量級數據搜索功能