文章目錄
歡迎訪問筆者個人技術博客:http://rukihuang.xyz/
1. 映射
1.1 字段類型(type)
1.1.1 字符串
1.1.1.1 text
- 指定分析器
analyzer
會對文本進行分詞
“name”: {
"type": "text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart",
"index": true,
"store": false
}
-
ik_max_word
:最大粒度 -
ik_smart
:智能- 索引時使用
ik_max_word
將搜索內容進行細粒度分詞,搜索時使用ik_smart
提高搜索精確性
- 索引時使用
-
index
:指定是否索引,默認爲index=true
,即要進行索引,只有進行索引纔可以從索引庫搜索到。 -
store
:是否在source
之外存儲,每個文檔索引後會在 ES中保存一份原始文檔,存放在"_source
"中,一般情況下不需要設置store
爲true
,因爲在_source
中已經有一份原始文檔了。
1.1.1.2 keyword
keyword
字段爲關鍵字字段,通常搜索keyword
是按照整體搜索,所以創建keyword字段的索引時是不進行分詞的,比如:郵政編碼、手機號碼、身份證等。keyword
字段通常用於過濾、排序、聚合等。
1.1.2 date日期類型
- 日期類型不用設置分詞器。通常日期類型的字段用於排序。
{
"properties": {
"timestamp": {
"type": "date",
"format": "yyyy‐MM‐dd HH:mm:ss||yyyy‐MM‐dd"
}
}
}
format
:設置日期格式
1.1.3 數值類型
-
儘量選擇範圍小的類型,提高搜索效率
-
對於浮點數儘量用比例因子
scaling_factor
- 假如比例因子爲100,如果我們輸入的價格是23.45則ES中會將23.45乘以100存儲在ES中。
- 如果輸入的價格是23.456,ES會將23.456乘以100再取一個接近原始值的數,得出2346。
- 使用比例因子的好處是整型比浮點型更易壓縮,節省磁盤空間。
- 如果比例因子不適合,則從下表選擇範圍小的去用:
"price": {
"type": "scaled_float",
"scaling_factor": 100
}
2 索引管理
2.1 搭建工程
2.1.1 ES客戶端
- ES提供多種不同的客戶端:
TransportClient
。ES提供的傳統客戶端,官方計劃8.0版本刪除此客戶端。RestClient
。RestClient
是官方推薦使用的,它包括兩種:Java Low Level REST Client
和Java High Level REST Client
。
- ES在6.0之後提供
Java High Level REST Client
, 兩種客戶端官方更推薦使用Java High Level REST Client
,不過當
前它還處於完善中,有些功能還沒有。 - 添加依賴
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.2.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.2.1</version>
</dependency>
2.1.2 配置文件application.yml
server:
port: ${port:40100}
spring:
application:
name: xc-search-service
xuecheng:
elasticsearch:
hostlist: ${eshostlist:127.0.0.1:9200} #多個結點中間用逗號分隔
2.1.3 配置類 ElasticsearchConfig
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Administrator
* @version 1.0
**/
@Configuration
public class ElasticsearchConfig {
@Value("${xuecheng.elasticsearch.hostlist}")
private String hostlist;
@Bean
public RestHighLevelClient restHighLevelClient(){
//解析hostlist配置信息
String[] split = hostlist.split(",");
//創建HttpHost數組,其中存放es主機和端口的配置信息
HttpHost[] httpHostArray = new HttpHost[split.length];
for(int i=0;i<split.length;i++){
String item = split[i];
httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
}
//創建RestHighLevelClient客戶端
return new RestHighLevelClient(RestClient.builder(httpHostArray));
}
//項目主要使用RestHighLevelClient,對於低級的客戶端暫時不用
@Bean
public RestClient restClient(){
//解析hostlist配置信息
String[] split = hostlist.split(",");
//創建HttpHost數組,其中存放es主機和端口的配置信息
HttpHost[] httpHostArray = new HttpHost[split.length];
for(int i=0;i<split.length;i++){
String item = split[i];
httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
}
return RestClient.builder(httpHostArray).build();
}
}
2.2 java api
2.2.1 創建索引
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestIndex {
@Autowired
private RestHighLevelClient client;
@Autowired
private RestClient restClient;
//創建索引庫
@Test
public void testCreacteIndex() throws IOException {
//創建索引對象
CreateIndexRequest createIndexRequest = new CreateIndexRequest("xc_course");
//設置參數
createIndexRequest.settings(Settings.builder().put("number_of_shards", "1").put("number_of_replicas", "0"));
//指定映射
createIndexRequest.mapping("doc", "{\n" +
"\t\"properties\": {\n" +
"\t\t\"studymodel\": {\n" +
"\t\t\t\"type\": \"keyword\"\n" +
"\t\t},\n" +
"\t\t\"name\":{\n" +
"\t\t\t\"type\": \"keyword\"\t\n" +
"\t\t},\n" +
"\t\t\"description\":{\n" +
"\t\t\t\"type\": \"text\",\t\n" +
"\t\t\t\"analyzer\": \"ik_max_word\",\t\n" +
"\t\t\t\"search_analyzer\": \"ik_smart\"\n" +
"\t\t},\n" +
"\t\t\"pic\":{\n" +
"\t\t\t\"type\": \"text\",\n" +
"\t\t\t\"index\": false\n" +
"\t\t}\n" +
"\t}\n" +
"}", XContentType.JSON);
//操作索引客戶端
IndicesClient indicesClient = client.indices();
//執行創建索引庫
CreateIndexResponse createIndexResponse = indicesClient.create(createIndexRequest);
//得到響應
boolean isSuccess = createIndexResponse.isAcknowledged();
System.out.println(isSuccess);
}
}
2.2.2 刪除索引
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestIndex {
@Autowired
private RestHighLevelClient client;
@Autowired
private RestClient restClient;
//刪除索引庫
@Test
public void testDeleteIndex() throws IOException {
//刪除索引請求對象
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("xc_course");
//刪除索引(發起刪除請求)
//操作索引的客戶端
IndicesClient indicesClient = client.indices();
//執行刪除
DeleteIndexResponse deleteIndexResponse = indicesClient.delete(deleteIndexRequest);
//刪除索引響應結果
boolean isSuccess = deleteIndexResponse.isAcknowledged();
System.out.println(isSuccess);
}
}
2.2.3 添加文檔
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestIndex {
@Autowired
private RestHighLevelClient client;
@Autowired
private RestClient restClient;
//添加文檔
@Test
public void testAddDoc() throws IOException {
//準備文檔
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("name", "spring cloud實戰");
jsonMap.put("description", "本課程主要從四個章節進行講解:1.微服務架構入門。2.spring cloud 實戰。3.實戰spring。4.。。");
jsonMap.put("studymodel", "201001");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
jsonMap.put("timestamp", dateFormat.format(new Date()));
jsonMap.put("price", 5.6f);
//創建請求
IndexRequest indexRequest = new IndexRequest("xc_course", "doc");
//指定文檔內容
indexRequest.source(jsonMap);
//通過client進行http請求
IndexResponse indexResponse = client.index(indexRequest);
//響應結果
DocWriteResponse.Result result = indexResponse.getResult();
System.out.println(result);
}
}
2.2.4 查詢文檔
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestIndex {
@Autowired
private RestHighLevelClient client;
@Autowired
private RestClient restClient;
//查詢文檔
@Test
public void testGetDoc() throws IOException {
//創建請求
GetRequest getRequest = new GetRequest("xc_course", "doc", "O4dlV3AB70vpNQQ-8OJA");
//發起請求
GetResponse getResponse = client.get(getRequest);
//得到文檔內容
Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
System.out.println(sourceAsMap);
}
}
2.2.5 更新文檔
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestIndex {
@Autowired
private RestHighLevelClient client;
@Autowired
private RestClient restClient;
//更新文檔
@Test
public void testUpdateDoc() throws IOException {
//創建請求
UpdateRequest updateRequest = new UpdateRequest("xc_course", "doc", "O4dlV3AB70vpNQQ-8OJA");
//待更新的內容
Map<String, String> map = new HashMap<>();
map.put("name", "spring cloud實戰修改後");
updateRequest.doc(map);
//發起請求
UpdateResponse updateResponse = client.update(updateRequest);
RestStatus status = updateResponse.status();
System.out.println(status);
}
}
2.2.6 根據Id刪除文檔
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestIndex {
@Autowired
private RestHighLevelClient client;
@Autowired
private RestClient restClient;
//根據Id刪除文檔
@Test
public void testDeleteDoc() throws IOException {
//刪除文檔的Id
String id = "O4dlV3AB70vpNQQ-8OJA";
//創建請求
DeleteRequest deleteRequest = new DeleteRequest("xc_course", "doc", id);
//發起請求
DeleteResponse deleteResponse = client.delete(deleteRequest);
//響應結果
DocWriteResponse.Result result = deleteResponse.getResult();
System.out.println(result);
}
}