一:安裝:
1)在linux下載並安裝elasticsearch在虛擬機上
2)增加用戶 sudo adduser username 然後切換用戶 sudo username(root用戶不能啓動服務)
3)對elasticsearch文件權限進行修改。chown usergroup:name elasticsearch -R(授權)
4)進入config文件夾,對文件配置 vim jvm.options 設置最大最小堆內存。然後 vim elasticsearch.yml設置data文件夾和logs文件夾(ES對虛擬機存儲佔用比較大)
5) 進入bin目錄 運行腳本 ./elasticsearch
二:操作
1.pom文件,版本很重要,不然起都起不來
<!-- Spring Boot Elasticsearch 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!--需要引入transport-netty3-client,否則會啓動報錯-->
<dependency>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty3-client</artifactId>
<version>5.6.10</version>
</dependency>
2.配置Bean
@Configuration
public class ElasticSearchConfig {
private static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class);
@PostConstruct
void init() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
}
@Bean
public TransportClient transportClient() {
logger.info("初始化");
TransportClient client = null;
try {
TransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName("localhost"),
Integer.valueOf(9300));
// 配置信息
Settings esSetting = Settings.builder()
.put("cluster.name","elasticsearch") //節點名稱
.build();
//配置信息Settings自定義
client = new PreBuiltTransportClient(esSetting);
client.addTransportAddresses(transportAddress);
} catch (Exception e) {
logger.error("elasticsearch TransportClient create error!!!", e);
}
return client;
}
}
3.實體類
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName="chuyun",type="article",indexStoreType="fs",shards=5,replicas=1,refreshInterval="-1")
public class Article {
//文章ID,這裏必須爲 id
@Id
private Long id;
//標題
private String title;
//內容
private String content;
//瀏覽量
private Integer viewCount;
//發佈時間
private Date createTime;
//更新時間
private Date updateTime;
}
dao層 //不用實現
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
List<Article> findByTitle(String title);
}
4.測試類
package top.hkf.demo.redistest.demo;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.junit4.SpringRunner;
import top.hkf.demo.dao.ArticleRepository;
import top.hkf.demo.entity.Article;
import org.springframework.data.domain.Page;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ESTest {
@Autowired
private ArticleRepository articleRepository;
@Autowired
private ElasticsearchTemplate template;
@Test
public void initRepositoryData() {
template.createIndex(Article.class);//創建索引庫
Article article = new Article();
article.setId((long) 1);
article.setTitle("xxx");
article.setContent("aaa,bbb,ccc");
article.setCreateTime(new Date());
article.setUpdateTime(new Date());
article.setViewCount(678);
articleRepository.save(article);
}
@Test
public void findDistinctByTitleContainingOrContentContainingTest() throws Exception {
String title = "xxx";
List<Article> list = articleRepository.findByTitle(title);
// List<Long> collect = list.stream().filter(article -> {
// return article.getId() > 5;
// }).map(Article::getId).collect(Collectors.toList());
}
//自定義查詢,根據命名規則
@Test
public void findByTitleAndContent() {
Pageable pageable = PageRequest.of(0, 2);//分頁,從0開始,不分頁默認沒頁10條
articleRepository.findByTitleAndContent("zs", "123", pageable);
}
//先分詞,在查詢,分詞之間是and關係,即所有分詞都應在一段話中
//需求是隻要包含任何一個詞即可查出來,即queryString,queryTerm
@Test
public void testNativeSearchQuery() {
//創建查詢對象
NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.queryStringQuery("123").defaultField("title"))
.withPageable(PageRequest.of(0, 3)).build();
//執行查詢
List<Article> articles = template.queryForList(nativeSearchQuery, Article.class);
articles.forEach(a -> System.out.println(a));
}
//高亮顯示,字段,前綴,後綴。在執行查詢之前設置高亮顯示
@Test
public void testFilter() {
List<Article> list=Arrays.asList(new Article(1l,"123","123"),
new Article(5l,"123","123"),
new Article(6l,"123","123"),
new Article(7l,"123","123"),
new Article(8l,"123","123"));
list.stream().filter(article ->
article.getId() > 5
).map(Article::getId).collect(Collectors.toList()).forEach(a-> System.out.println(a));
}
}
執行成功後,head裏面就會有索引庫,索引庫的定義在實體類中。
註解說明:
@Documnet 註解
public @interface Document {
String indexName(); //索引庫的名稱,個人建議以項目的名稱命名
String type() default ""; //類型,個人建議以實體的名稱命名
short shards() default 5; //默認分區數
short replicas() default 1; //每個分區默認的備份數
String refreshInterval() default "1s"; //刷新間隔
String indexStoreType() default "fs"; //索引文件存儲類型
}
@Field註解
public @interface Field {
FieldType type() default FieldType.Auto; //自動檢測屬性的類型,可以根據實際情況自己設置
FieldIndex index() default FieldIndex.analyzed; //默認情況下分詞,一般默認分詞就好,除非這個字段你確定查詢時不會用到
DateFormat format() default DateFormat.none; //時間類型的格式化
String pattern() default "";
boolean store() default false; //默認情況下不存儲原文
String searchAnalyzer() default ""; //指定字段搜索時使用的分詞器
String indexAnalyzer() default ""; //指定字段建立索引時指定的分詞器
String[] ignoreFields() default {}; //如果某個字段需要被忽略
boolean includeInParent() default false;
}
總結:錯誤1
java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4]
在注入bean時,執行
@PostConstruct
void init() {
System.setProperty("es.set.netty.runtime.available.processors", "false");
}
錯誤2:java訪問端口爲9300,http訪問爲9200