Springboot項目集成Elasticsearch

1、Kibana指令說明

1.1 查詢索引

查詢所有索引

GET _cat/indices

 查詢索引mapper

GET gov_search_web/_mapper

查詢索引配置

GET government_governmentsearch/_settings

1.2 創建索引

DELETE  /gov_search_web3
PUT /gov_search_web3
{ 
   "mappings": {
      "question": {
        "properties": {
          "id": {
            "type": "keyword"
          },
          "question": {
            "type": "text"
          },
          "answer": {
             "type": "text"
          },
          "updateTime": {
            "type": "long"
          }
        }
      }
    }
}

1.3 查詢指定索引下的所有數據

GET gov_search_web/nlp/_search
{
  "query": {
    "match_all": {}
  }
}

1.4 精確查詢索引下的數據

GET government_governmentsearch/governmentsearch/_search
{
  "query": {
    "term": {
      "category": "07"
    }
  }
}

1.5 精確查詢多個值

GET government_governmentsearch/governmentsearch/_search
{
  "query": {
    "terms": {
      "category": ["01", "07"]
    }
  }
}

1.6 條件刪除文檔

POST government_governmentsearch/governmentsearch/_delete_by_query
{
  "query": {
    "match": {"id": "ff80808160179faa016024c8b4ac60bc"}
  }
}

1.7 多條件查詢


GET government_governmentsearch/governmentsearch/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "category": "07"
          }
        },
        {
          "match": {
            "title": "公積金提取"
          }
        }
      ]
    }
  }
}

1.8 插入數據

POST gov_yiqing/xqjkzkdj/123
{
  "id": "123",
  "name": "111",
  "gender": "1",
  "mobile": "15001233210",
  "idCard": "111111222233334444"
}

1.9 備份索引到一個新索引中去

創建新索引

遷移老索引的數據到新索引中

POST _reindex
{
  "source": {
    "index": "index_old"
  },
  "dest": {
    "index": "index_old_new"
  }
}

1.10 查詢非空和排序

GET akm_show_his/_search
{
  "query": {
    "bool": {
      "must_not": {
        "exists": {
          "field": "jzdCityCode"
        }
      }
    }
  },
  "sort": [
    {
      "createTime": {
        "order": "desc"
      }
    }
  ]
}

2、 索引及索引模板

2.1 索引模板

屬性 說明
order 當存在多個索引模板時並且某個索引兩者都匹配時,settings和mpapings將合成一個配置應用在這個索引上。合併的順序可由索引模板的order屬性來控制。
index_patterns 索引前綴

total_shards_per_node

每個節點的分片數,最多設置爲3個

refresh_interval

每個索引的刷新頻率,刷新間隔爲-1代表關閉數據刷新。

number_of_shards

總分片數,節點數乘3

translog.flush_threshold_size

當事務日誌大小到達此預設值,則執行flush。(默認512mb)
translog.sync_interval translog多久被同步到磁盤並提交一次,默認5秒。
translog.durability

是否在每次index,delete,update,bulk請求之後立即同步並提交translog:

  • request  :(默認)fsync and commit after every request。這就意味着,如果發生崩潰,那麼所有隻要是已經確認的寫操作都已經被提交到磁盤。
  • async  :在後臺每sync_interval時間進行一次fsync和commit。意味着如果發生崩潰,那麼所有在上一次自動提交以後的已確認的寫操作將會丟失。

slowlog

慢日誌閾值設置

注意:Elasticsearch7.X 移除了類型(type),使用的是默認的_doc

PUT _template/akm_template
{
  "order": 0,
  "index_patterns": [
    "akm*"
  ],
  "settings": {
    "index": {
	  "routing": {
        "allocation": {
          "total_shards_per_node": "3"
        }
      },
      "refresh_interval": "30s",
      "number_of_shards": "9",
      "translog": {
        "flush_threshold_size": "256mb",
        "sync_interval": "30s",
        "durability": "async"
      },
      "indexing": {
        "slowlog": {
          "threshold": {
            "index": {
              "warn": "100ms",
              "debug": "20ms",
              "info": "30ms"
            }
          }
        }
      },
      "search": {
        "slowlog": {
          "threshold": {
            "fetch": {
              "warn": "500ms",
              "debug": "100ms",
              "info": "200ms"
            },
            "query": {
              "warn": "2s",
              "debug": "500ms",
              "info": "1s"
            }
          }
        }
      }
    }
  },
  "mappings": {},
  "aliases": {}
}

2.2、索引

DELETE  akm_show_his
PUT /akm_show_his
{
    "mappings":{
        "properties":{
            "id":{
                "type":"keyword"
            },
            "userName":{
                "type":"text"
            },
            "idCardNo":{
                "type":"text"
            },
            "userPhone":{
                "type":"text"
            }   "type":"text"
            },
            "createTime":{
                "type":"long"
            }
        }
    }
}

 3、項目集成ES說明

3.1 升級springboot版本

對於Elasticsearch7.X版本,需要升級springboot版本在2.2.0以上

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

3.2 引入elasticsearch依賴

在pom文件中,添加Elasticsearch依賴

<!-- 集成es -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

3.3 增加配置文件

Elasticsearch有兩種連接方式:transport、rest。transport通過TCP方式訪問ES(只支持java),rest方式通過http API 訪問ES(沒有語言限制)。

Elasticsearch7.X版本不建議使用transport方式,在8.X的版本中將要廢棄。

在配置文件的時候,就需要配置ES的http端口,如下:

# ----- es配置 -----------
elasticsearch:
  rest:
    uris: ip1:port1,ip2:port2,ip3:port3  #es連接的http地址端口
    connection-timeout: 6s #連接超時

3.4 Dto類

@Data
@Document(indexName = "#{indexConfig.showIndexName}", type = "_doc")
public class EsShowHisDto {

    @Id
    @Field(type = FieldType.Keyword)
    private String id;

    @Field(type = FieldType.Text)
    private String userName;

    /**
     * 證件號碼
     */
    @Field(type = FieldType.Text)
    private String idCardNo;

    /**
     * 手機號
     */
    @Field(type = FieldType.Text)
    private String userPhone;

    /**
     * 現居住地
     */
    @Field(type = FieldType.Text)
    private String addressNow;

    /**
     * 健康狀態
     */
    @Field(type = FieldType.Text)
    private String healthStatus;

    /**
     * 創建時間
     */
    @Field(type = FieldType.Long)
    private Long createTime;

    /**
     * 健康信息表id
     */
    @Field(type = FieldType.Text)
    private String healthId;

    /**
     * 經度
     */
    @Field(type = FieldType.Text)
    private String longitudeNum;

    /**
     * 緯度
     */
    @Field(type = FieldType.Text)
    private String latitudeNum;

    /**
     * 編碼
     */
    @Field(type = FieldType.Text)
    private String adminDiv;

    /**
     * 居住地區縣CODE
     */
    @Field(type = FieldType.Text)
    private String jzdQxCode;

    /**
     * 居住地街道CODE
     */
    @Field(type = FieldType.Text)
    private String jzdJdCode;

    /**
     * 居住地社區CODE
     */
    @Field(type = FieldType.Text)
    private String jzdSqCode;

    /**
     * 來源地省CODE
     */
    @Field(type = FieldType.Text)
    private String lydProvCode;

    /**
     * 來源地市CODE
     */
    @Field(type = FieldType.Text)
    private String lydCityCode;

    /**
     * 來源地區縣CODE
     */
    @Field(type = FieldType.Text)
    private String lydQxCode;

    /**
     * 來源地街道CODE
     */
    @Field(type = FieldType.Text)
    private String lydJdCode;

    /**
     * 來源地社區CODE
     */
    @Field(type = FieldType.Text)
    private String lydSqCode;

    @Field(type = FieldType.Text)
    private String curHealthStatus;

    @Field(type = FieldType.Text)
    private String belongarea;

    /**
     * 是否刪除  1:是  0:否
     */
    @Field(type = FieldType.Text)
    private String isDelete;

    /**
     * 居住地市級CODE
     */
    @Field(type = FieldType.Text)
    private String jzdCityCode;
}

3.5 Dao類

public interface EsShowHisDao extends ElasticsearchRepository<EsShowHisDto, String> {

}

3.6 Service類

查詢ES數據

BoolQueryBuilder : 聚合分組查詢

SortBuilder :排序,unmapped_type不設置時,如果source中不包含createTime元素,查詢會返回錯誤信息,設置時,可以使用默認值填充

Pageable :分頁

@Override
public PageResultBean<EsShowHisDto> queryFromEs(EsQueryDto esQueryDto) {
    // 查詢
    BoolQueryBuilder query = handleParam(esQueryDto);
    // 排序
    SortBuilder sortBuilder = SortBuilders.fieldSort("createTime").unmappedType("long").order(SortOrder.DESC);
    // 分頁
    int pageNum = esQueryDto.getPageNum() == null ? 0 : esQueryDto.getPageNum();
    int pageSize = (esQueryDto.getPageSize() == null || esQueryDto.getPageSize()>100) ? 10 : esQueryDto.getPageSize();
    Pageable pageable = PageRequest.of(pageNum, pageSize);

    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).withSort(sortBuilder).withPageable(pageable).build();
    //查詢結果
    Page<EsShowHisDto> searchPageResults = esShowHisDao.search(searchQuery);
    return new PageResultBean<>(searchPageResults);
}

刪除ES數據

批量刪除ES裏的數據,需要先通過條件查詢出來,再進行刪除操作。

ES索引有個設置max_result_window,默認是10000,最多刪除一萬條數據。

@Override
public String deleteFromEs(EsShowHisDto esShowHisDto, String areYouSure) {
    if (esShowHisDto == null) {
        return "param empty";
    }
    // 查詢
    BoolQueryBuilder query = QueryBuilders.boolQuery();
    if (StringUtils.isNotEmpty(esShowHisDto.getIdCardNo())) {
        query.must(QueryBuilders.termQuery("idCardNo", esShowHisDto.getIdCardNo()));
    }
    if (StringUtils.isNotEmpty(esShowHisDto.getId())) {
        query.must(QueryBuilders.termQuery("id", esShowHisDto.getId()));
    }
    if (StringUtils.isNotEmpty(esShowHisDto.getBelongarea())) {
        query.must(QueryBuilders.termQuery("belongarea", esShowHisDto.getBelongarea()));
    }
    //查詢結果
    Iterable<EsShowHisDto> iterable = esShowHisDao.search(query);
    esShowHisDao.deleteAll(iterable);
    return "success";
}

6.7 動態索引

1、創建索引模板,保證所有以akm爲前綴的索引都有相同的setting。

2、索引Dto裏面的indexName設置動態配置

@Document(indexName = "#{indexConfig.showIndexName}", type = "_doc")
public class EsShowHisDto {

    @Id
    @Field(type = FieldType.Keyword)
    private String id;

    @Field(type = FieldType.Text)
    private String userName;

3、添加索引名的配置類,設置默認值

@Data
@Component
public class IndexConfig {

    @Value("${akm.esIndex.showHis:akm_show_his}")
    private String showIndexName;

    @Value("${akm.esIndex.inoutHis:akm_inout_his}")
    private String inoutIndexName;

    @Value("${akm.esIndex.checkHis:akm_check_his}")
    private String checkIndexName;

}

4、在往ES裏插入數據的時候,通過set配置類IndexConfig的索引名的值,來實現動態的往不同的索引裏插入數據。索引的數據結構一致,若索引在ES裏不存在,則會新增。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章