一 準備工作
下載elasticsearch-6.7.0和展示ES數據的界面工具elasticsearch-head-master,本人電腦已安裝IntelliJ IDEA 2019.3 x64的java工具。
簡單點,我們直接按默認配置學習。
windows直接點擊elasticsearch.bat啟動ES。
使用npm run start啟動elasticsearch-head-master,然後就可以從界面上查看ES數據。
二 java操作入庫ES數據
1、引入elasticsearch包
<!-- ElasticSearch連接-->
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>${searchbox.version}</version>
</dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
2、將庫表裡的數據導入部分到ES上
public void testSave() throws IOException {
//對象 ArticleHomeDto是要存入ES裡的欄位設置
ArticleHomeDto dto = new ArticleHomeDto();
dto.setSize(50);
dto.setTag("__all__");
//從mysql資料庫裡查出要存入ES的內容
List<ApArticle> apArticles = apArticleMapper.loadArticleListByLocation(dto, (short)0);
//開始循環入庫到ES
for (ApArticle apArticle : apArticles) {
ApArticleContent apArticleContent = apArticleContentMapper.selectByArticleId(apArticle.getId());
EsIndexEntity esIndexEntity = new EsIndexEntity();
esIndexEntity.setChannelId(new Long(apArticle.getChannelId()));
esIndexEntity.setId(apArticle.getId().longValue());
esIndexEntity.setContent(ZipUtils.gunzip(apArticleContent.getContent()));
esIndexEntity.setPublishTime(apArticle.getPublishTime());
esIndexEntity.setStatus(new Long(1));
esIndexEntity.setTag("article");
esIndexEntity.setTitle(apArticle.getTitle());
Index.Builder builder = new Index.Builder(esIndexEntity);
builder.id(apArticle.getId().toString());
builder.refresh(true);
Index index = builder.index(ESIndexConstants.ARTICLE_INDEX).type(ESIndexConstants.DEFAULT_DOC).build();
JestResult result = jestClient.execute(index);
if (result != null && !result.isSucceeded()) {
throw new RuntimeException(result.getErrorMessage() + "插入更新索引失敗!");
}
最終入庫到ES內容如下:
三 ES上查看操作數據
1、基本查詢:查詢某個欄位是否包含某內容,match
2、複合查詢:查詢某條數據
3、複合查詢:查詢包含關鍵信息的數據,查詢包含「極客頭條」的數據
4、複合查詢:查詢包含關鍵信息的數據,只要滿足一條即可查出來
5、複合查詢:查詢包含關鍵信息的數據,must和should混合使用
四總結
本節簡單介紹了windows環境下如何安裝ES,如何用java導入數據到ES,並且在ES界面上查詢ES裡的數據,同樣我們也可以在ES上操作數據,用put命令實現增刪改操作。