使用spring 的es,有兩種方式,一種是node
先說第一種,第一種相對而言功能更復雜,支持聚合,模糊,正則查詢。mysql
1. 引入maven的依賴,這裏注意你安裝的elasticsearch的服務器版本與spring data elasticsearch 版本的對照關係。spring
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> <version>1.3.6.RELEASE</version> </dependency>
2. 在spring啓動加載的xml配置bean。sql
<!--es鏈接配置--> <elasticsearch:transport-client id="es_client" cluster-name="elasticsearch_jcobsns_daily" cluster-nodes="192.168.69.238:9300,192.168.69.239:9300"/> <!--es template--> <bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <constructor-arg name="client" ref="es_client"/> </bean>
3. 編寫存儲數據的對象 (構造函數必須保留一個無參的)服務器
@Document(indexName = "my_test",type = "ppp") public class ESDomain { @Id private Long id ; @Field private Integer age ; @Field(type = FieldType.String,index = FieldIndex.analyzed) private String author ; @Field(type = FieldType.String ,index = FieldIndex.analyzed) private String views ; public ESDomain() { } public ESDomain(Long id, Integer age, String author, String views) { this.id = id; this.age = age; this.author = author; this.views = views; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getViews() { return views; } public void setViews(String views) { this.views = views; } }
1. @Document
做用在類,標記實體類爲文檔對象,通常有兩個屬性elasticsearch
indexName:對應索引庫名稱,type:對應在索引庫中的類型,shards:分片數量,默認5,replicas:副本數量,默認1maven
2. @Id
做用在成員變量,標記一個字段做爲id主鍵函數
3. @Field
做用在成員變量,標記爲文檔的字段,並指定字段映射屬性:工具
type:字段類型,取值是枚舉:FieldType,index:是否索引,布爾類型,默認是true,store:是否存儲,布爾類型,默認是false,analyzer:分詞器名稱ui
4. 存儲一個對象,並創建該對象索引
elasticsearchTemplate.index(indexQuery);
5. 批量存儲多個對象
elasticsearchTemplate.bulkIndex(queries);
6. 查詢
查詢須要傳一個 SearchQuery 的對象。該對象構造方法以下:
NativeSearchQuery query = new NativeSearchQueryBuilder() .withIndices("my_test2")//index .withTypes("ppp2")//type .withQuery(boolQuery)//查詢條件 .withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC))//排序 .withPageable(new PageRequest(0, 200))//分頁 .build();
查詢條件須要實現QueryBuilder接口:
通常由這個工具類建立:QueryBuilders ,經常使用的有:
QueryBuilders.boolQuery() ;//判斷條件查詢,能夠組合多條件。相似mysql的where QueryBuilders.matchPhraseQuery() ;//匹配查詢 QueryBuilders.regexpQuery() ;//正則查詢 QueryBuilders.wildcardQuery() ;//支持* ?的匹配查詢
使用ElasticsearchRepository方式:繼承類ElasticsearchRepository
public interface ESDomainElasticsearchRepository extends ElasticsearchRepository<ESDomain , Long> { }
在spring.xml 中配置加載
<elasticsearch:repositories base-package="com.my.es.manager"/>
CURD直接調ESDomainElasticsearchRepository對應的save,update,find就行。