spring boot整合elasticsearch7.x

spring boot整合elasticsearch7.x

引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.9.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.9.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.9.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.plugin</groupId>
    <artifactId>transport-netty4-client</artifactId>
    <version>7.9.0</version>
</dependency>

配置

@Configuration
public class ElasticSearchConfig {

    @Bean
    public RestHighLevelClient elasticsearchClient(){
        ClientConfiguration configuration = ClientConfiguration.builder()
                .connectedTo("192.168.xxx.xxxx:9200")
                .build();
        return RestClients.create(configuration).rest();
    }

}


在使用的地方直接注入 RestHighLevelClient实例:


@Autowired
private RestHighLevelClient client;


private static final String INDEX_NAME = "abc";

...

索引操作

创建索引


@Test
public void indexCreateTest() throws IOException {
    CreateIndexRequest request = new CreateIndexRequest(INDEX_NAME);
    CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(response));
}

结果:

{
	"acknowledged": true,
	"fragment": false,
	"shardsAcknowledged": true
}

索引是否存在


@Test
public void indexExistTest() throws IOException {
    GetIndexRequest request = new GetIndexRequest(INDEX_NAME);
    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    System.out.println("exist: " + exists);
}

删除索引

@Test
public void indexDelTest() throws IOException {
    DeleteIndexRequest request = new DeleteIndexRequest(INDEX_NAME);
    AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(response));
}

结果:

{
	"acknowledged": true,
	"fragment": false
}

document文档操作

先创建几个Bean:

@Data
public class User {

    @Id
    private String id;
    private String name;
    private int age;
    private List<String> hobbies;
    private Address address;

}

@Data
public class Address {

    private String city;
    private String street;
    private Point location;
}

@Data
@AllArgsConstructor
public class Point {

    private long lat;
    private long lon;
}


插入文档


@Test
public void docCreateTest() throws IOException {

    User user = new User();
    user.setId("1");
    user.setName("测试");
    user.setAge(10);
    user.setHobbies(Arrays.asList("car","ball"));
    Address address = new Address();
    address.setCity("上海");
    address.setStreet("天河路");
    Point location = new Point(19923,3232);
    address.setLocation(location);
    user.setAddress(address);

    IndexRequest request = new IndexRequest(INDEX_NAME);
    request.id(user.getId()).timeout(TimeValue.timeValueSeconds(1));
    request.source(JSON.toJSONString(user), XContentType.JSON);
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(response));
}

结果:

{
	"fragment": false,
	"id": "1",
	"index": "abc",
	"primaryTerm": 1,
	"result": "CREATED",
	"seqNo": 0,
	"shardId": {
		"fragment": true,
		"id": -1,
		"index": {
			"fragment": false,
			"name": "abc",
			"uUID": "_na_"
		},
		"indexName": "abc"
	},
	"shardInfo": {
		"failed": 0,
		"failures": [],
		"fragment": false,
		"successful": 1,
		"total": 2
	},
	"type": "_doc",
	"version": 1
}

根据id查询


@Test
public void docGetTest() throws IOException {
    GetRequest request = new GetRequest(INDEX_NAME, "1");
    GetResponse response = client.get(request, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(response));
}

结果:


{
	"exists": true,
	"fields": {},
	"fragment": false,
	"id": "1",
	"index": "abc",
	"primaryTerm": 1,
	"seqNo": 0,
	"source": {
		"address": {
			"city": "上海",
			"street": "天河路",
			"location": {
				"lon": 3232,
				"lat": 19923
			}
		},
		"hobbies": ["car", "ball"],
		"name": "测试",
		"id": "1",
		"age": 10
	},
	"sourceAsBytes": "eyJhZGRyZXNzIjp7ImNpdHkiOiLkuIrmtbciLCJsb2NhdGlvbiI6eyJsYXQiOjE5OTIzLCJsb24iOjMyMzJ9LCJzdHJlZXQiOiLlpKnmsrPot68ifSwiYWdlIjoxMCwiaG9iYmllcyI6WyJjYXIiLCJiYWxsIl0sImlkIjoiMSIsIm5hbWUiOiLmtYvor5UifQ==",
	"sourceAsBytesRef": {
		"fragment": true
	},
	"sourceAsMap": {
		"$ref": "$.source"
	},
	"sourceAsString": "{\"address\":{\"city\":\"上海\",\"location\":{\"lat\":19923,\"lon\":3232},\"street\":\"天河路\"},\"age\":10,\"hobbies\":[\"car\",\"ball\"],\"id\":\"1\",\"name\":\"测试\"}",
	"sourceEmpty": false,
	"sourceInternal": {
		"$ref": "$.sourceAsBytesRef"
	},
	"type": "_doc",
	"version": 1
}


根据id更新文档


/**
    * 不为空则 更新
    * @throws IOException
    */
@Test
public void docUpdTest() throws IOException {

    UpdateRequest request = new UpdateRequest(INDEX_NAME, "1");

    User user = new User();
    user.setId("1");
    user.setName("3测试");
    user.setAge(220);
    user.setHobbies(Arrays.asList("car","ball"));
    Address address = new Address();
    address.setCity("上海");
    address.setStreet("诸光路");
    Point location = new Point(19923,3232);
    address.setLocation(location);
    user.setAddress(address);

    request.doc(JSON.toJSONString(user), XContentType.JSON);
    UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(response));
}

结果:

{
	"fragment": false,
	"id": "1",
	"index": "abc",
	"primaryTerm": 1,
	"result": "UPDATED",
	"seqNo": 1,
	"shardId": {
		"fragment": true,
		"id": -1,
		"index": {
			"fragment": false,
			"name": "abc",
			"uUID": "_na_"
		},
		"indexName": "abc"
	},
	"shardInfo": {
		"failed": 0,
		"failures": [],
		"fragment": false,
		"successful": 1,
		"total": 2
	},
	"type": "_doc",
	"version": 2
}

在es中查询一下:

GET /abc/_doc/1

{
  "_index" : "abc",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 2,
  "_seq_no" : 1,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "address" : {
      "city" : "上海",
      "location" : {
        "lat" : 19923,
        "lon" : 3232
      },
      "street" : "诸光路"
    },
    "age" : 220,
    "hobbies" : [
      "car",
      "ball"
    ],
    "id" : "1",
    "name" : "3测试"
  }
}

发现version变成了2

删除文档


@Test
public void docDelTest() throws IOException {

    DeleteRequest request = new DeleteRequest(INDEX_NAME, "1");
    DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(response));
}

结果:


{
	"fragment": false,
	"id": "1",
	"index": "abc",
	"primaryTerm": 1,
	"result": "DELETED",
	"seqNo": 2,
	"shardId": {
		"fragment": true,
		"id": -1,
		"index": {
			"fragment": false,
			"name": "abc",
			"uUID": "_na_"
		},
		"indexName": "abc"
	},
	"shardInfo": {
		"failed": 0,
		"failures": [],
		"fragment": false,
		"successful": 1,
		"total": 2
	},
	"type": "_doc",
	"version": 3
}

在es中 查询一下:

GET /abc/_doc/1

{
  "_index" : "abc",
  "_type" : "_doc",
  "_id" : "1",
  "found" : false
}

批量插入


@Test
public void docBatchInsertTest() throws IOException {

    BulkRequest request = new BulkRequest();
    request.timeout("10s");
    for (int i = 0; i < 10; i++) {
        User user = new User();
        user.setId(i+"");
        user.setName("测试"+i);
        user.setAge(10+i);
        user.setHobbies(Arrays.asList("car","ball"));
        Address address = new Address();
        address.setCity("上海");
        address.setStreet("诸光路");
        Point location = new Point(19923+i,3232+i);
        address.setLocation(location);
        user.setAddress(address);
        request.add(new IndexRequest(INDEX_NAME).id(""+(i+1)).source(JSON.toJSONString(user), XContentType.JSON));
    }
    BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
    System.out.println(JSON.toJSONString(response));
}


在es中查询一下:

GET /abc/_search

结果:


{
  "took" : 454,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 10,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "abc",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "address" : {
            "city" : "上海",
            "location" : {
              "lat" : 19923,
              "lon" : 3232
            },
            "street" : "诸光路"
          },
          "age" : 10,
          "hobbies" : [
            "car",
            "ball"
          ],
          "id" : "0",
          "name" : "测试0"
        }
      },
      {
        "_index" : "abc",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "address" : {
            "city" : "上海",
            "location" : {
              "lat" : 19924,
              "lon" : 3233
            },
            "street" : "诸光路"
          },
          "age" : 11,
          "hobbies" : [
            "car",
            "ball"
          ],
          "id" : "1",
          "name" : "测试1"
        }
      }
      ...
  }
}

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页