elasticsearch的使用
elasticsearch的使用
索引管理
1、創(chuàng)建索引
對(duì)比關(guān)系型數(shù)據(jù)庫(kù),創(chuàng)建索引相當(dāng)于創(chuàng)建數(shù)據(jù)庫(kù)
-
url:
http:/ip:9200/test -
方式:PUT

不允許重復(fù)put相同索引
2、獲取索引
a、將請(qǐng)求方式改為get即獲取當(dāng)前索引信息
-
url:
ip:9200/test -
方式:GET

b、獲取所有索引信息
-
url:
ip:9200/_cat/indices?v -
方式:GET

3、刪除索引
將請(qǐng)求方式改為delete即刪除當(dāng)前索引信息
-
url:
ip:9200/test -
方式:DELETE
文檔管理
1、創(chuàng)建文檔
-
url:
ip:9200/test/_doc/1001或者是ip:9200/test/_create/1001的post請(qǐng)求 -
方式:POST
-
請(qǐng)求體:
{ "title": "小米", "price": 1999 }
若不指定id會(huì)自動(dòng)創(chuàng)建id

2、文檔查詢
a、主鍵查詢
將請(qǐng)求方式改為get即獲取當(dāng)前文檔信息
-
url:
ip:9200/test/_doc/1002 -
方式:GET

b、獲取索引中所有文檔
-
url:
ip:9200/test/_search -
方式:GET 請(qǐng)求體必須為空

3、文檔修改
a、全部覆蓋
-
url:
ip:9200/test/_doc/1001 -
方式:PUT
-
請(qǐng)求體:
{ "title": "小米", "price": 2000 }

b、局部覆蓋
-
url:
ip:9200/test/_update/1001 -
方式:POST
-
請(qǐng)求體:
{ "doc":{ "title": "小米", "price": 11 } }

4、文檔刪除
-
url:
ip:9200/test/_doc/1001 -
方式:DELETE
5、文檔參數(shù)條件查詢
a、路徑方式查詢
-
url:
ip:9200/test/_search?q=title:oppo -
方式:GET
返回結(jié)果
{
"took": 409,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.8923234,
"hits": [
{
"_index": "test",
"_type": "_doc",
"_id": "1001",
"_score": 1.8923234,
"_source": {
"title": "oppo",
"price": 2222
}
}
]
}
}
b、請(qǐng)求體攜帶參數(shù)方式查詢
-
url:
ip:9200/test/_search -
方式:GET
-
請(qǐng)求體:
{ "query":{ "match":{ "title":"oppo" } } }
精確匹配(數(shù)字)使用term
全文檢索使用match
完整包含使用match_phrase
精確匹配含使用match查詢字段后添加(.keyword)
c、請(qǐng)求體攜帶參數(shù)方式查詢?nèi)繑?shù)據(jù)
-
url:
ip:9200/test/_search -
方式:GET
-
請(qǐng)求體:
{ "query":{ "match_all":{ } } }
6、文檔參數(shù)分頁(yè)查詢排序
-
url:
ip:9200/test/_search -
方式:GET
-
請(qǐng)求體:
{
"query":{
"match_all":{
}
},
"from":0, // 偏移量
"size":2, // 查詢數(shù)量
"_source":["title"], // 只查詢的字段
"sort":{
"price":{ //排序字段
"order": "asc" //排序正序倒序
}
}
}
7、文檔多條件查詢,范圍查詢
-
url:
ip:9200/test/_search -
方式:GET
-
請(qǐng)求體:
{
"query":{
"bool":{
"must":[ // must 相當(dāng)于 and 數(shù)組中的條件必須全部滿足
{
"match":{
"title":"oppo"
}
},{
"match":{
"price":2222
}
}
],
"should":[ // should相當(dāng)于 or
{
"match":{
"title":"小米"
}
}
],
"filter":{ // 范圍查詢
"range":{
"price":{
"gt":1000
}
}
}
}
}
}
8、文檔模糊查詢
a、分詞模糊查詢
-
url:
ip:9200/test/_search -
方式:GET
-
請(qǐng)求體:
{
"query":{
"match":{
"title":"小米"
}
}
}
返回結(jié)果
{
"took": 341,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 4,
"relation": "eq"
},
"max_score": 2.7208898,
"hits": [
{
"_index": "test",
"_type": "_doc",
"_id": "16",
"_score": 2.7208898,
"_source": {
"title": "小米",
"price": 666
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "17",
"_score": 2.7208898,
"_source": {
"title": "小米",
"price": 777
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "15",
"_score": 1.8103764,
"_source": {
"title": "op小米po",
"price": 55
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "18",
"_score": 1.254745,
"_source": {
"title": "小紅",
"price": 777
}
}
]
}
}
b、全匹配模糊查詢
-
url:
ip:9200/test/_search -
方式:GET
-
請(qǐng)求體:
{
"query":{
"match_phrase":{
"title":"小米"
}
}
}
返回結(jié)果
{
"took": 48,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 3,
"relation": "eq"
},
"max_score": 2.72089,
"hits": [
{
"_index": "test",
"_type": "_doc",
"_id": "16",
"_score": 2.72089,
"_source": {
"title": "小米",
"price": 666
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "17",
"_score": 2.72089,
"_source": {
"title": "小米",
"price": 777
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "15",
"_score": 1.8103766,
"_source": {
"title": "op小米po",
"price": 55
}
}
]
}
}
小紅就沒了
c、高亮顯示
-
url:
ip:9200/test/_search -
方式:GET
-
請(qǐng)求體:
{
"query":{
"match_phrase":{
"title":"小米"
}
},
"highlight":{
"fields":{
"title":{}
}
}
}
返回結(jié)果
{
"took": 155,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 3,
"relation": "eq"
},
"max_score": 2.72089,
"hits": [
{
"_index": "test",
"_type": "_doc",
"_id": "16",
"_score": 2.72089,
"_source": {
"title": "小米",
"price": 666
},
"highlight": {
"title": [
"<em>小</em><em>米</em>"
]
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "17",
"_score": 2.72089,
"_source": {
"title": "小米",
"price": 777
},
"highlight": {
"title": [
"<em>小</em><em>米</em>"
]
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "15",
"_score": 1.8103766,
"_source": {
"title": "op小米po",
"price": 55
},
"highlight": {
"title": [
"op<em>小</em><em>米</em>po"
]
}
}
]
}
}
9、文檔聚合查詢
a、分組
-
url:
ip:9200/test/_search -
方式:GET
-
請(qǐng)求體:
{
"aggs":{ //聚合操作
"price_group":{ // 分鐘名稱
"terms":{ // 分組
"field": "price" // 分組字段
}
}
}
}
返回結(jié)果
{
"took": 111,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 20,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "test",
"_type": "_doc",
"_id": "1",
"_score": 1.0,
"_source": {
"title": "vivo",
"price": 999
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "1002",
"_score": 1.0,
"_source": {
"title": "華為",
"price": 1999
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "1001",
"_score": 1.0,
"_source": {
"title": "oppo",
"price": 2222
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "2",
"_score": 1.0,
"_source": {
"title": "vivo2",
"price": 999
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "3",
"_score": 1.0,
"_source": {
"title": "vivo3",
"price": 999
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "4",
"_score": 1.0,
"_source": {
"title": "vivo4",
"price": 999
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "5",
"_score": 1.0,
"_source": {
"title": "vivo5",
"price": 999
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "6",
"_score": 1.0,
"_source": {
"title": "apple",
"price": 999
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "7",
"_score": 1.0,
"_source": {
"title": "aifeng",
"price": 999
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "8",
"_score": 1.0,
"_source": {
"title": "lisis",
"price": 999
}
}
]
},
"aggregations": {
"price_group": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [
{
"key": 999,
"doc_count": 8
},
{
"key": 777,
"doc_count": 3
},
{
"key": 55,
"doc_count": 2
},
{
"key": 11,
"doc_count": 1
},
{
"key": 454,
"doc_count": 1
},
{
"key": 666,
"doc_count": 1
},
{
"key": 1999,
"doc_count": 1
},
{
"key": 2222,
"doc_count": 1
},
{
"key": 3333,
"doc_count": 1
},
{
"key": 4541,
"doc_count": 1
}
]
}
}
}
b、平均值
-
url:
ip:9200/test/_search -
方式:GET
-
請(qǐng)求體:
{
"aggs":{ //聚合操作
"price_avg":{ // 分鐘名稱
"avg":{ // 分組
"field": "price" // 分組字段
}
}
}
}
結(jié)果
{
"aggs":{
"price_group":{
"avg":{
"field": "price"
}
}
},
"size":0
}
映射關(guān)系
映射關(guān)系不能刪除只能創(chuàng)建新的索引,數(shù)據(jù)遷移到新的映射
1、創(chuàng)建索引
-
url:
ip:9200/user -
方式:PUT
2、創(chuàng)建映射關(guān)系
-
url:
ip:9200/user/_mapping -
方式:PUT
-
請(qǐng)求體:
{
"properties":{
"name":{ // 字段
"type":"text", // 分詞模糊查詢
"index":"true" // 可索引查詢
},
"sex":{
"type":"keyword",
"index":"true"
},
"tel":{
"type":"keyword",// 全匹配模糊查詢查詢7
"index":"false"http:// 不可索引查詢
}
}
}
可get查看映射
3、創(chuàng)建文檔

4、查詢文檔
name可分詞查,sex全匹配查,tel不可查
javaApi 整合springBoot
依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.8.0</version>
</dependency>
配置yml
spring:
elasticsearch:
rest:
uris: ip:9200
username: elasticsearch
password: xxx
創(chuàng)建文檔類
@Document 指定索引信息
@Field(type = FieldType.Text) 設(shè)置分詞模糊查詢
@Document(indexName = "exam-question-index")
public class ExamQuestionDocument {
private static final long serialVersionUID = 1L;
/**
* 主鍵
*/
@Id
private Long id;
/**
* 試題內(nèi)容以及選項(xiàng)
*/
@Field(type = FieldType.Text)
private String qstContentAndOpts;
public ExamQuestionDocument() {
}
public ExamQuestionDocument(Long id, String qstContentAndOpts) {
this.id = id;
this.qstContentAndOpts = qstContentAndOpts;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getQstContentAndOpts() {
return qstContentAndOpts;
}
public void setQstContentAndOpts(String qstContentAndOpts) {
this.qstContentAndOpts = qstContentAndOpts;
}
@Override
public String toString() {
return "ExamQuestionDocument{" +
"id=" + id +
", qstContentAndOpts='" + qstContentAndOpts + '\'' +
'}';
}
}
工具類
@Component
public class ElasticSearchUtil {
@Resource
private ElasticsearchRestTemplate elasticsearchRestTemplate;
/**
* 創(chuàng)建索引
* @param clazz 包含Document注解并指定索引名稱
* @return 是否創(chuàng)建成功
*/
public Boolean createIndex(Class<?> clazz){
// 索引名稱只能是lowerCase
IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(clazz);
//創(chuàng)建索引
if (indexOperations.create()){
//生成映射
Document mapping = indexOperations.createMapping();
//推送映射
return indexOperations.putMapping(mapping);
}
return false;
}
/**
* 獲取索引信息
* @param clazz 包含Document注解并指定索引名稱
* @return 索引信息
*/
public IndexOperations getIndex(Class<?> clazz){
return elasticsearchRestTemplate.indexOps(clazz);
}
/**
* 刪除索引
* @param clazz 包含Document注解并指定索引名稱
* @return 是否刪除成功
*/
public Boolean deleteIndex(Class<?> clazz){
IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(clazz);
return indexOperations.delete();
}
/**
* 創(chuàng)建文檔
* @param data 文檔數(shù)據(jù)
* @param docId 文檔id (id存在則會(huì)覆蓋)
* @param IndexName 索引名稱
* @return 是否創(chuàng)建成功
*/
public String createDocument(Object data,String docId,String IndexName){
IndexQuery indexQuery = new IndexQuery();
// 設(shè)置文檔內(nèi)容
indexQuery.setObject(data);
// 設(shè)置文檔id
indexQuery.setId(docId);
// 添加文檔到指定索引
return elasticsearchRestTemplate.doIndex(indexQuery, IndexCoordinates.of(IndexName));
}
/**
* 批量創(chuàng)建文檔
* @param indexQueryList 文檔數(shù)據(jù)
* @param IndexName 索引名稱
*/
public void createDocument(List<IndexQuery> indexQueryList,String IndexName){
// 添加文檔到指定索引
elasticsearchRestTemplate.bulkIndex(indexQueryList, IndexCoordinates.of(IndexName));
}
/**
* 根據(jù)文檔id獲取文檔
* @param id 文檔id
* @param indexName 索引名稱
* @param tClass 文檔類class
* @param <T> 文檔類型
* @return 文檔
*/
public <T> T getDocumentById(String id,String indexName,Class<T> tClass){
IdsQueryBuilder idsQueryBuilder = QueryBuilders.idsQuery();
idsQueryBuilder.addIds(id);
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withQuery(idsQueryBuilder)
.build();
SearchHit<T> itemSearchHit = elasticsearchRestTemplate
.searchOne(query, tClass, IndexCoordinates.of(indexName));
assert itemSearchHit != null;
return itemSearchHit.getContent();
}
/**
* 根據(jù)文檔id獲取指定字段文檔
* @param id 文檔id
* @param indexName 索引名稱
* @param tClass 文檔類class
* @param fields 文檔指定獲取字段
* @param <T> 文檔類型
* @return 文檔
*/
public <T> T getDocumentById(String id,String indexName,Class<T> tClass,String... fields){
IdsQueryBuilder idsQueryBuilder = QueryBuilders.idsQuery();
idsQueryBuilder.addIds(id);
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withQuery(idsQueryBuilder)
.withFields(fields)
.build();
SearchHit<T> itemSearchHit = elasticsearchRestTemplate
.searchOne(query, tClass, IndexCoordinates.of(indexName));
assert itemSearchHit != null;
return itemSearchHit.getContent();
}
/**
* 刪除文檔
* @param id 文檔id
* @param clazz 包含Document注解并指定索引名稱
* @return 是否刪除成功
*/
public String deleteDocument(String id,Class<?> clazz){
return elasticsearchRestTemplate.delete(id, clazz);
}
/**
* 分詞查詢指定字段文檔
* @param queryColumn 請(qǐng)求字段
* @param queryData 模糊查詢數(shù)據(jù)
* @param indexName 索引名稱
* @param tClass 文檔類class
* @param <T> 文檔類型
* @return 模糊查詢返回值
*/
public <T> SearchHits<T> queryLikeDocumentByField(String queryColumn,String queryData,String indexName,Class<T> tClass){
BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
// 多條件查詢
// 分詞查詢 查詢字段需要添加@Field(type = FieldType.Text)注解
queryBuilder
.must(QueryBuilders.matchQuery(queryColumn, queryData))
// 過濾
// .filter()
;
// 高亮處理, 其實(shí)就是拼接<span/>標(biāo)簽, 瀏覽器會(huì)自動(dòng)解析該標(biāo)簽
HighlightBuilder.Field highlightField = new HighlightBuilder.Field(queryColumn)
// 設(shè)置為red
.preTags("<span style=\"color:red\">")
.postTags("</span>");
Query query = new NativeSearchQueryBuilder()
.withQuery(queryBuilder)
// post_filter, 查詢后過濾結(jié)果
// .withFilter(queryBuilder)
// 分頁(yè)
//.withPageable(PageRequest.of(0, 10))
// 返回字段
//.withFields("id","qstContent")
// 排序
// .withSort()
// 聚合
// .addAggregation()
// 高亮
.withHighlightFields(highlightField)
.build();
return elasticsearchRestTemplate.search(query, tClass, IndexCoordinates.of(indexName));
}
}
浙公網(wǎng)安備 33010602011771號(hào)