SpringBoot menyambung ke ElasticSearch Terdapat empat cara arus perdana:
Kaedah 1 : Sambung ke pelayan es melalui Klien Pengangkutan Elastik Lapisan asas adalah berdasarkan protokol TCP dan berkomunikasi dengan pelayan ES jauh melalui modul pengangkutan Walau bagaimanapun, secara rasmi tidak disyorkan untuk menggunakannya bermula dari V7.0 dan akan dikeluarkan secara rasmi bermula dari V8.0.
Kaedah 2: Sambungkan ke pelayan ES melalui Elastic Java Low Level Rest Client Lapisan asas berkomunikasi dengan pelayan ES jauh melalui API yang tenang berdasarkan protokol HTTP paling mudah dan paling asas disediakan. API adalah serupa dengan logik operasi API yang diperkenalkan kepada anda dalam artikel sebelumnya.
Kaedah 3: Sambung ke pelayan es melalui Elastic Java High Level Rehat Client Lapisan bawah dikapsulkan berdasarkan Elastic Java Low Level Rehat Client untuk menyediakan API yang lebih maju. Dan ia selaras dengan antara muka dan parameter Klien Pengangkutan Elastik Ia adalah pelanggan es yang disyorkan secara rasmi.
Kaedah 4: Sambung ke pelayan es melalui klien JestClient Ini adalah klien es yang dibangunkan oleh komuniti sumber terbuka berdasarkan protokol HTTP reka bentuk adalah lebih baik daripada Rehat yang disediakan secara rasmi oleh ES Pelanggan adalah lebih ringkas, lebih munasabah, dan lebih mudah digunakan Ia mempunyai keserasian tertentu dengan versi pelayan ES, tetapi kelajuan kemas kini tidak begitu pantas Versi ES semasa telah dikeluarkan V7.9, tetapi JestClient hanya menyokong versi ES V1.0~V6.X.
Ada satu lagi perkara yang semua orang perlu beri perhatian, dan itu ialah keserasian nombor versi!
Semasa proses pembangunan, semua orang perlu memberi perhatian khusus kepada nombor versi pelanggan dan pelayan, dan memastikannya sekonsisten yang mungkin, contohnya, nombor versi pelayan ialah 6.8.2 , maka nombor versi pelanggan yang disambungkan ke es , sebaik-baiknya 6.8.2 Walaupun ia tidak boleh konsisten kerana sebab projek, nombor versi pelanggan mestilah antara 6.0.0 dan 6.8.2, dan tidak boleh melebihi versi pelayan. nombor, supaya klien dapat mengekalkan operasi normal, jika tidak banyak masalah akan berlaku, jika klien adalah versi 7.0.4, program akan melaporkan pelbagai ralat pada masa ini, malah tidak boleh digunakan! >Mengapa anda melakukan ini? Sebab utama adalah versi yang lebih tinggi tidak serasi dengan versi yang lebih rendah daripada struktur parameter permintaan API es6 dan es7, jadi nombor versi pelanggan dan pelayan harus kekal konsisten. seboleh mungkin.
Tiada lagi perkara karut, mari terus ke kod!
2 Amalan kod
2.1. Import dependensi
<!--elasticsearch--> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>6.4.2</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>6.4.2</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>6.4.2</version> </dependency>
elasticsearch.scheme=http elasticsearch.address=127.0.0.1:9200 elasticsearch.userName= elasticsearch.userPwd= elasticsearch.socketTimeout=5000 elasticsearch.connectTimeout=5000 elasticsearch.connectionRequestTimeout=5000
2.3. Cipta kelas konfigurasi elasticsearch
@Configuration public class ElasticsearchConfiguration { private static final Logger log = LoggerFactory.getLogger(ElasticsearchConfiguration.class); private static final int ADDRESS_LENGTH = 2; @Value("${elasticsearch.scheme:http}") private String scheme; @Value("${elasticsearch.address}") private String address; @Value("${elasticsearch.userName}") private String userName; @Value("${elasticsearch.userPwd}") private String userPwd; @Value("${elasticsearch.socketTimeout:5000}") private Integer socketTimeout; @Value("${elasticsearch.connectTimeout:5000}") private Integer connectTimeout; @Value("${elasticsearch.connectionRequestTimeout:5000}") private Integer connectionRequestTimeout; /** * 初始化客户端 * @return */ @Bean(name = "restHighLevelClient") public RestHighLevelClient restClientBuilder() { HttpHost[] hosts = Arrays.stream(address.split(",")) .map(this::buildHttpHost) .filter(Objects::nonNull) .toArray(HttpHost[]::new); RestClientBuilder restClientBuilder = RestClient.builder(hosts); // 异步参数配置 restClientBuilder.setHttpClientConfigCallback(httpClientBuilder -> { httpClientBuilder.setDefaultCredentialsProvider(buildCredentialsProvider()); return httpClientBuilder; }); // 异步连接延时配置 restClientBuilder.setRequestConfigCallback(requestConfigBuilder -> { requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout); requestConfigBuilder.setSocketTimeout(socketTimeout); requestConfigBuilder.setConnectTimeout(connectTimeout); return requestConfigBuilder; }); return new RestHighLevelClient(restClientBuilder); } /** * 根据配置创建HttpHost * @param s * @return */ private HttpHost buildHttpHost(String s) { String[] address = s.split(":"); if (address.length == ADDRESS_LENGTH) { String ip = address[0]; int port = Integer.parseInt(address[1]); return new HttpHost(ip, port, scheme); } else { return null; } } /** * 构建认证服务 * @return */ private CredentialsProvider buildCredentialsProvider(){ final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, userPwd)); return credentialsProvider; } }
2.4. Pengurusan indeks
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class IndexJunit {
@Autowired
private RestHighLevelClient client;
/**
* 创建索引(简单模式)
* @throws IOException
*/
@Test
public void createIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("cs_index");
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}
/**
* 创建索引(复杂模式)
* 可以直接把对应的文档结构也一并初始化
* @throws IOException
*/
@Test
public void createIndexComplete() throws IOException {
CreateIndexRequest request = new CreateIndexRequest();
//索引名称
request.index("cs_index");
//索引配置
Settings settings = Settings.builder()
.put("index.number_of_shards", 3)
.put("index.number_of_replicas", 1)
.build();
request.settings(settings);
//映射结构字段
Map<String, Object> properties = new HashMap();
properties.put("id", ImmutableBiMap.of("type", "text"));
properties.put("name", ImmutableBiMap.of("type", "text"));
properties.put("sex", ImmutableBiMap.of("type", "text"));
properties.put("age", ImmutableBiMap.of("type", "long"));
properties.put("city", ImmutableBiMap.of("type", "text"));
properties.put("createTime", ImmutableBiMap.of("type", "long"));
Map<String, Object> mapping = new HashMap<>();
mapping.put("properties", properties);
//添加一个默认类型
System.out.println(JSON.toJSONString(request));
request.mapping("_doc",mapping);
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class IndexJunit {
@Autowired
private RestHighLevelClient client;
/**
* 删除索引
* @throws IOException
*/
@Test
public void deleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("cs_index1");
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ElasticSearchApplication.class)
public class IndexJunit {
@Autowired
private RestHighLevelClient client;
/**
* 查询索引
* @throws IOException
*/
@Test
public void getIndex() throws IOException {
// 创建请求
GetIndexRequest request = new GetIndexRequest();
request.indices("cs_index");
// 执行请求,获取响应
GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
System.out.println(response.toString());
}
}
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ElasticSearchApplication.class) public class IndexJunit { @Autowired private RestHighLevelClient client; /** * 检查索引是否存在 * @throws IOException */ @Test public void exists() throws IOException { // 创建请求 GetIndexRequest request = new GetIndexRequest(); request.indices("cs_index"); // 执行请求,获取响应 boolean response = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println(response); } }
Soal sama ada indeks itu wujud
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ElasticSearchApplication.class) public class IndexJunit { @Autowired private RestHighLevelClient client; /** * 查询所有的索引名称 * @throws IOException */ @Test public void getAllIndices() throws IOException { GetAliasesRequest request = new GetAliasesRequest(); GetAliasesResponse response = client.indices().getAlias(request,RequestOptions.DEFAULT); Map<String, Set<AliasMetaData>> map = response.getAliases(); Set<String> indices = map.keySet(); for (String key : indices) { System.out.println(key); } } }
Soal semua nama indeks
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ElasticSearchApplication.class) public class IndexJunit { @Autowired private RestHighLevelClient client; /** * 查询索引映射字段 * @throws IOException */ @Test public void getMapping() throws IOException { GetMappingsRequest request = new GetMappingsRequest(); request.indices("cs_index"); request.types("_doc"); GetMappingsResponse response = client.indices().getMapping(request, RequestOptions.DEFAULT); System.out.println(response.toString()); } }
Soal medan pemetaan indeks
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ElasticSearchApplication.class) public class IndexJunit { @Autowired private RestHighLevelClient client; /** * 添加索引映射字段 * @throws IOException */ @Test public void addMapping() throws IOException { PutMappingRequest request = new PutMappingRequest(); request.indices("cs_index"); request.type("_doc"); //添加字段 Map<String, Object> properties = new HashMap(); properties.put("accountName", ImmutableBiMap.of("type", "keyword")); Map<String, Object> mapping = new HashMap<>(); mapping.put("properties", properties); request.source(mapping); PutMappingResponse response = client.indices().putMapping(request, RequestOptions.DEFAULT); System.out.println(response.isAcknowledged()); } }
Tambah medan pemetaan indeks
ublic class UserDocument { private String id; private String name; private String sex; private Integer age; private String city; private Date createTime; //省略get、set... }2.5. Pengurusan dokumenDokumen yang dipanggil adalah untuk menambah data pada indeks untuk memudahkan pertanyaan data kandungan operasi, sila Lihat di bawah!
Tambah dokumen
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ElasticSearchApplication.class) public class DocJunit { @Autowired private RestHighLevelClient client; /** * 添加文档 * @throws IOException */ @Test public void addDocument() throws IOException { // 创建对象 UserDocument user = new UserDocument(); user.setId("1"); user.setName("里斯"); user.setCity("武汉"); user.setSex("男"); user.setAge(20); user.setCreateTime(new Date()); // 创建索引,即获取索引 IndexRequest request = new IndexRequest(); // 外层参数 request.id("1"); request.index("cs_index"); request.type("_doc"); request.timeout(TimeValue.timeValueSeconds(1)); // 存入对象 request.source(JSON.toJSONString(user), XContentType.JSON); // 发送请求 System.out.println(request.toString()); IndexResponse response = client.index(request, RequestOptions.DEFAULT); System.out.println(response.toString()); } }rrree
Kemas kini dokumen
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ElasticSearchApplication.class) public class DocJunit { @Autowired private RestHighLevelClient client; /** * 更新文档(按需修改) * @throws IOException */ @Test public void updateDocument() throws IOException { // 创建对象 UserDocument user = new UserDocument(); user.setId("2"); user.setName("程咬金"); user.setCreateTime(new Date()); // 创建索引,即获取索引 UpdateRequest request = new UpdateRequest(); // 外层参数 request.id("2"); request.index("cs_index"); request.type("_doc"); request.timeout(TimeValue.timeValueSeconds(1)); // 存入对象 request.doc(JSON.toJSONString(user), XContentType.JSON); // 发送请求 System.out.println(request.toString()); UpdateResponse response = client.update(request, RequestOptions.DEFAULT); System.out.println(response.toString()); } }
Padam dokumen
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ElasticSearchApplication.class) public class DocJunit { @Autowired private RestHighLevelClient client; /** * 删除文档 * @throws IOException */ @Test public void deleteDocument() throws IOException { // 创建索引,即获取索引 DeleteRequest request = new DeleteRequest(); // 外层参数 request.id("1"); request.index("cs_index"); request.type("_doc"); request.timeout(TimeValue.timeValueSeconds(1)); // 发送请求 System.out.println(request.toString()); DeleteResponse response = client.delete(request, RequestOptions.DEFAULT); System.out.println(response.toString()); } }
Soal sama ada dokumen itu wujud
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ElasticSearchApplication.class) public class DocJunit { @Autowired private RestHighLevelClient client; /** * 查询文档是不是存在 * @throws IOException */ @Test public void exists() throws IOException { // 创建索引,即获取索引 GetRequest request = new GetRequest(); // 外层参数 request.id("3"); request.index("cs_index"); request.type("_doc"); // 发送请求 System.out.println(request.toString()); boolean response = client.exists(request, RequestOptions.DEFAULT); System.out.println(response); } }
Soal dokumen yang ditentukan melalui ID
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ElasticSearchApplication.class) public class DocJunit { @Autowired private RestHighLevelClient client; /** * 通过ID,查询指定文档 * @throws IOException */ @Test public void getById() throws IOException { // 创建索引,即获取索引 GetRequest request = new GetRequest(); // 外层参数 request.id("1"); request.index("cs_index"); request.type("_doc"); // 发送请求 System.out.println(request.toString()); GetResponse response = client.get(request, RequestOptions.DEFAULT); System.out.println(response.toString()); } }
Tambah dokumen dalam kelompokrreeee
Atas ialah kandungan terperinci Cara SpringBoot+Elasticsearch melaksanakan carian data. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!