| package com.example; |
| |
| import com.alibaba.fastjson.JSON; |
| import com.alibaba.fastjson.JSONObject; |
| import com.example.dto.Person; |
| import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; |
| 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.action.index.IndexRequest; |
| import org.elasticsearch.action.index.IndexResponse; |
| import org.elasticsearch.action.search.SearchRequest; |
| import org.elasticsearch.action.search.SearchResponse; |
| import org.elasticsearch.action.support.master.AcknowledgedResponse; |
| import org.elasticsearch.client.IndicesClient; |
| import org.elasticsearch.client.RequestOptions; |
| 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 org.elasticsearch.cluster.metadata.MappingMetadata; |
| import org.elasticsearch.common.unit.TimeValue; |
| import org.elasticsearch.common.xcontent.XContentBuilder; |
| import org.elasticsearch.common.xcontent.XContentFactory; |
| import org.elasticsearch.common.xcontent.XContentType; |
| import org.elasticsearch.index.query.BoolQueryBuilder; |
| import org.elasticsearch.index.query.QueryBuilders; |
| import org.elasticsearch.index.query.RangeQueryBuilder; |
| import org.elasticsearch.index.query.TermQueryBuilder; |
| import org.elasticsearch.search.SearchHit; |
| import org.elasticsearch.search.SearchHits; |
| import org.elasticsearch.search.aggregations.Aggregation; |
| import org.elasticsearch.search.aggregations.AggregationBuilders; |
| import org.elasticsearch.search.aggregations.Aggregations; |
| import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms; |
| import org.elasticsearch.search.aggregations.bucket.terms.Terms; |
| import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; |
| import org.elasticsearch.search.aggregations.metrics.Sum; |
| import org.elasticsearch.search.aggregations.metrics.SumAggregationBuilder; |
| import org.elasticsearch.search.builder.SearchSourceBuilder; |
| import org.elasticsearch.search.sort.FieldSortBuilder; |
| import org.elasticsearch.search.sort.SortBuilders; |
| import org.elasticsearch.search.sort.SortMode; |
| import org.junit.jupiter.api.Test; |
| import org.springframework.beans.factory.annotation.Autowired; |
| import org.springframework.boot.test.context.SpringBootTest; |
| |
| import java.io.IOException; |
| import java.util.Date; |
| import java.util.HashMap; |
| import java.util.List; |
| import java.util.Map; |
| import java.util.concurrent.TimeUnit; |
| |
| @SpringBootTest |
| class ElasticSearchApplicationTests { |
| @Autowired |
| RestHighLevelClient client; |
| |
| @Test |
| void contextLoads() { |
| System.out.println(client); |
| } |
| |
| |
| @Test |
| public void createIndex() throws IOException { |
| IndicesClient indices = client.indices(); |
| CreateIndexRequest createIndexRequest = new CreateIndexRequest("index_test"); |
| CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT); |
| System.out.println(createIndexResponse.isAcknowledged()); |
| } |
| |
| |
| @Test |
| public void addIndexMapping() throws IOException { |
| IndicesClient indices = client.indices(); |
| CreateIndexRequest createIndexRequest = new CreateIndexRequest("index_test_one"); |
| String mapping = "{\n" + " \"properties\" : {\n" + " \"address\" : {\n" + " \"type\" : \"text\",\n" + " \"analyzer\" : \"ik_max_word\"\n" + " },\n" + " \"age\" : {\n" + " \"type\" : \"long\"\n" + " },\n" + " \"name\" : {\n" + " \"type\" : \"keyword\"\n" + " }\n" + " }\n" + " }"; |
| createIndexRequest.mapping(mapping, XContentType.JSON); |
| CreateIndexResponse createIndexResponse = indices.create(createIndexRequest, RequestOptions.DEFAULT); |
| |
| System.out.println(createIndexResponse.isAcknowledged()); |
| } |
| |
| |
| @Test |
| public void createIndexAddMapping() throws Exception { |
| IndicesClient indices = client.indices(); |
| XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("properties").startObject().field("name").startObject().field("index", "true").field("type", "keyword").endObject().field("money").startObject().field("index", "true").field("type", "double").endObject().field("birthday").startObject().field("index", "true").field("type", "date").field("format", "strict_date_optional_time||epoch_millis").endObject().endObject().endObject(); |
| CreateIndexRequest createIndexRequest = new CreateIndexRequest("index_test"); |
| createIndexRequest.mapping(builder); |
| CreateIndexResponse response = indices.create(createIndexRequest, RequestOptions.DEFAULT); |
| System.out.println(response.isAcknowledged()); |
| |
| } |
| |
| |
| @Test |
| public void getIndex() throws IOException { |
| IndicesClient indices = client.indices(); |
| |
| GetIndexRequest getIndexRequest = new GetIndexRequest("index_test_one"); |
| GetIndexResponse getIndexResponse = indices.get(getIndexRequest, RequestOptions.DEFAULT); |
| Map<String, MappingMetadata> mappings = getIndexResponse.getMappings(); |
| for (String key : mappings.keySet()) { |
| System.out.println("key:" + mappings.get(key).getSourceAsMap()); |
| } |
| } |
| |
| |
| @Test |
| public void deleteIndex() throws IOException { |
| IndicesClient indices = client.indices(); |
| DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("index_test"); |
| AcknowledgedResponse delete = indices.delete(deleteIndexRequest, RequestOptions.DEFAULT); |
| System.out.println(delete.isAcknowledged()); |
| } |
| |
| |
| @Test |
| public void existIndex() throws IOException { |
| IndicesClient indices = client.indices(); |
| GetIndexRequest getIndexRequest = new GetIndexRequest("index_test"); |
| boolean exists = indices.exists(getIndexRequest, RequestOptions.DEFAULT); |
| System.out.println(exists); |
| } |
| |
| |
| @Test |
| public void addDoc() throws IOException { |
| Map<String, Object> map = new HashMap<>(); |
| map.put("name", "小青"); |
| map.put("money", 300.00); |
| map.put("birthday", new Date()); |
| IndexRequest request = new IndexRequest("index_test").id("2").source(map); |
| IndexResponse res = client.index(request, RequestOptions.DEFAULT); |
| System.out.println(res.getId()); |
| } |
| |
| |
| @Test |
| public void addDoc2() throws Exception { |
| Person person = new Person(); |
| person.setId("4"); |
| person.setName("小李"); |
| person.setAge(20); |
| person.setAddress("江苏南京"); |
| String data = JSON.toJSONString(person); |
| |
| IndexRequest indexRequest = new IndexRequest("index_test_one").id(person.getId()).source(data, XContentType.JSON); |
| IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT); |
| System.out.println(response.getId()); |
| } |
| |
| |
| |
| @Test |
| public void UpdateDoc() throws Exception { |
| Person person = new Person(); |
| person.setId("4"); |
| person.setName("小李"); |
| person.setAge(20); |
| person.setAddress("中国"); |
| String data = JSON.toJSONString(person); |
| |
| IndexRequest indexRequest = new IndexRequest("index_test_one").id(person.getId()).source(data, XContentType.JSON); |
| IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT); |
| System.out.println(response.getId()); |
| } |
| |
| |
| @Test |
| public void getDocById() throws Exception { |
| GetRequest indexRequest = new GetRequest("index_test_one", "4"); |
| |
| GetResponse response = client.get(indexRequest, RequestOptions.DEFAULT); |
| System.out.println(response.getSourceAsMap()); |
| } |
| |
| |
| @Test |
| public void deleteDoc() throws IOException { |
| DeleteRequest deleteRequest = new DeleteRequest("index_test_one", "1"); |
| DeleteResponse respone = client.delete(deleteRequest, RequestOptions.DEFAULT); |
| System.out.println(respone.getId()); |
| |
| } |
| |
| |
| @Test |
| public void queryFind() throws IOException { |
| SearchRequest searchRequest = new SearchRequest("index_test_one"); |
| SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); |
| |
| TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "小王"); |
| |
| RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").from(19).to(20); |
| |
| |
| |
| |
| |
| |
| |
| FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("age"); |
| |
| fieldSortBuilder.sortMode(SortMode.MIN); |
| |
| |
| BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery().must(termQueryBuilder).should(rangeQueryBuilder); |
| sourceBuilder.query(boolQueryBuilder).sort(fieldSortBuilder); |
| |
| sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); |
| searchRequest.source(sourceBuilder); |
| |
| SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); |
| SearchHits hits = response.getHits(); |
| for (SearchHit hit : hits) { |
| String souceAsString = hit.getSourceAsString(); |
| JSONObject jsonObject = JSON.parseObject(souceAsString); |
| System.out.println(jsonObject); |
| } |
| } |
| |
| |
| @Test |
| public void aggregationQuery() throws Exception { |
| SearchRequest searchRequest = new SearchRequest("index_test_one"); |
| SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); |
| TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("by_age").field("age"); |
| sourceBuilder.aggregation(termsAggregationBuilder); |
| sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); |
| searchRequest.source(sourceBuilder); |
| |
| SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); |
| Aggregations aggregations = searchResponse.getAggregations(); |
| Map<String, Aggregation> stringAggregationMap = aggregations.getAsMap(); |
| ParsedLongTerms parsedLongTerms = (ParsedLongTerms) stringAggregationMap.get("by_age"); |
| List<? extends Terms.Bucket> buckets = parsedLongTerms.getBuckets(); |
| for (Terms.Bucket bucket : buckets) { |
| Long docCount = bucket.getDocCount(); |
| Number keyAsNumber = bucket.getKeyAsNumber(); |
| System.out.println(keyAsNumber + "岁的有" + docCount + "个"); |
| } |
| } |
| |
| |
| @Test |
| public void aggregationSum() throws Exception { |
| SearchRequest searchRequest = new SearchRequest("index_test"); |
| SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); |
| SumAggregationBuilder sumAggregationBuilder = AggregationBuilders.sum("money_total").field("money"); |
| sourceBuilder.aggregation(sumAggregationBuilder); |
| sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); |
| searchRequest.source(sourceBuilder); |
| |
| SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); |
| Aggregations aggregations = searchResponse.getAggregations(); |
| Sum moneyTotal = aggregations.get("money_total"); |
| Double moneyTotalDouble = moneyTotal.getValue(); |
| System.out.println(moneyTotalDouble); |
| } |
| |
| } |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能