转载请注明出处:http://blog.csdn.net/smartbetter/article/details/53535435
ElasticSearch 是一个基于 Lucene 的搜索服务器,是一个分布式、可扩展、实时的搜索与数据分析引擎,它能从项目一开始就赋予你的数据以搜索、分析和探索的能力,基于 RESTful web 接口。Elasticsearch 是用 Java 开发的,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。
1.Spring Boot整合Elasticsearch
需要添加 Maven 依赖:
<dependency>
<groupId>org.elasticsearchgroupId>
<artifactId>elasticsearchartifactId>
<version>5.6.3version>
dependency>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>transportartifactId>
<version>5.6.3version>
dependency>
<dependency>
<groupId>org.apache.logging.log4jgroupId>
<artifactId>log4j-coreartifactId>
<version>2.7version>
dependency>
在 Java 配置类中注册 bean:
@Bean
public TransportClient getTransportClient() throws UnknownHostException {
InetSocketTransportAddress node = new InetSocketTransportAddress(
InetAddress.getByName("192.168.2.20"), 9300
);
Settings settings = Settings.builder()
.put("cluster.name", "es")
.build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(node);
return client;
}
到此集成成功。
2.Elasticsearch基本用法
首先需要注入 TransportClient:
@Autowired
private TransportClient client;
查询:
GetResponse respOnse= client.prepareGet("book", "techbook", "1").get();
System.out.println(response.getSource());
创建:
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("title", "java8")
.field("author", "Tom")
.field("word_count", 1000)
.endObject();
IndexResponse respOnse= client.prepareIndex("book", "techbook")
.setSource(builder)
.get();
System.out.println(response.getResult() + ", id=" + response.getId());
删除:
DeleteResponse respOnse= client.prepareDelete("book", "techbook", "1").get();
System.out.println(response.getResult());
修改:
UpdateRequest request = new UpdateRequest("book", "techbook", "1");
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("title", "java9")
.endObject();
request.doc(builder);
UpdateResponse respOnse= client.update(request).get();
System.out.println(response.getResult());
复合查询:
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("author", "Tom"));
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("word_count")
.from("1000")
.to("5000");
boolQuery.filter(rangeQuery);
SearchResponse respOnse= client.prepareSearch("book")
.setTypes("techbook")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(boolQuery)
.setFrom(0)
.setSize(10)
.get();
System.out.println(response);