创建测试项目,导包
创建一个maven项目,导入ElasticSearch相关包
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.8</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.6.8</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.24</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
创建索引
@Test
public void createIndex() throws Exception{
Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build();
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.111.129"),9300));
client.admin().indices().prepareCreate("blog2").get();
client.close();
}
运行结果可以在elasticsearch-head-master中看到
创建映射mapping
因为无论创建索引还是mapping,以及之后的创建数据和查询操作都需要创建client连接对象,所以我们将其封装成一个单独的方法。此处注解Before的作用为在点击运行test之前都会限制行一遍getTransportClient()方法
TransportClient client ;
@Before
public void getTransportClient() throws UnknownHostException {
Settings settings = Settings.builder().put("cluster.name","my-elasticsearch").build();
client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.111.129"), 9300));
}
创建映射
@Test
public void createMappings() throws Exception {
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.startObject("article")
.startObject("properties")
.startObject("id")
.field("type","integer").field("store","yes")
.endObject()
.startObject("title")
.field("type","string").field("store","yes").field("analyzer","ik_smart")
.endObject()
.startObject("content")
.field("type","string").field("store","yes").field("analyzer","ik_smart")
.endObject()
.endObject()
.endObject()
.endObject();
PutMappingRequest mapping = Requests.putMappingRequest("blog2")
.type("article").source(builder);
client.admin().indices().putMapping(mapping).get();
client.close();
}
运行后可以在elasticsearch-head-master中看到
建立文档操作
建立文档1–通过XContentBuilder
此处要注意id格式默认为长整型
@Test
public void createDoc() throws Exception{
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("id", 2L)
.field("title","桂林大暴雨")
.field("content","桂林下雨了!桂林又下雨了!")
.endObject();
client.prepareIndex()
.setIndex("blog2")
.setType("article")
.setId("2")
.setSource(builder)
.get();
client.close();
}
可以在elasticsearch-head-master中看到
建立文档2–通过Jackson转换实体
字面意思通过传入对象的方式创建文档 首先创建Article实体类
public class Article {
private long id;
private String title;
private String content;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
然后使?Jackson转换实体
@Test
public void createDoc2() throws Exception{
Article article = new Article();
article.setId(3);
article.setTitle("桂林大暴雪");
article.setContent("这是不可能的!这是不可能的!");
ObjectMapper objectMapper = new ObjectMapper();
String jsonDocument = objectMapper.writeValueAsString(article);
System.out.println(jsonDocument);
client.prepareIndex("blog2","article","3")
.setSource(jsonDocument, XContentType.JSON)
.get();
}
同样可以在elasticsearch-head-master中看到,文档同样创建成功
查询文档操作
TermQuery
TermQuery:对搜索的关键词不分词
@Test
public void testQueryByTerm() throws Exception{
QueryBuilder queryBuilder = QueryBuilders.termQuery("title","桂林暴雪");
SearchResponse searchResponse = client.prepareSearch("blog2")
.setTypes("article")
.setQuery(queryBuilder)
.get();
SearchHits searchHits = searchResponse.getHits();
System.out.println("查询结果总记录数:"+searchHits.getTotalHits());
Iterator<SearchHit> iterator = searchHits.iterator();
while(iterator.hasNext()) {
SearchHit searchHit = iterator.next();
System.out.println(searchHit.getSourceAsString());
System.out.println("-----------?档的属性-----------");
Map<String, Object> document = searchHit.getSource();
System.out.println(document.get("id"));
System.out.println(document.get("title"));
System.out.println(document.get("content"));
}
client.close();
}
QueryString
query_string:搜索之前对搜索的关键词分词,搜索结果取决于分词器
@Test
public void testQueryByQueryString() throws Exception {
QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("桂林暴雪").defaultField("title");
SearchResponse searchResponse = client.prepareSearch("blog2")
.setTypes("article")
.setQuery(queryBuilder)
.get();
SearchHits searchHits = searchResponse.getHits();
System.out.println("查询结果总记录数:" + searchHits.getTotalHits());
Iterator<SearchHit> iterator = searchHits.iterator();
while(iterator.hasNext()) {
SearchHit searchHit = iterator.next();
System.out.println(searchHit.getSourceAsString());
System.out.println("-----------?档的属性-----------");
Map<String, Object> document = searchHit.getSource();
System.out.println(document.get("id"));
System.out.println(document.get("title"));
System.out.println(document.get("content"));
}
client.close();
}
MatchQuery
match查询时,对查询字符串会进行分词处理。
@Test
public void testQueryByMatchQuery() throws Exception {
QueryBuilder queryBuilder = QueryBuilders.matchQuery("title", "桂暴雪");
SearchResponse searchResponse = client.prepareSearch("blog2")
.setTypes("article")
.setQuery(queryBuilder)
.get();
SearchHits searchHits = searchResponse.getHits();
System.out.println("查询结果总记录数:" + searchHits.getTotalHits());
Iterator<SearchHit> iterator = searchHits.iterator();
while(iterator.hasNext()) {
SearchHit searchHit = iterator.next();
System.out.println(searchHit.getSourceAsString());
System.out.println("-----------?档的属性-----------");
Map<String, Object> document = searchHit.getSource();
System.out.println(document.get("id"));
System.out.println(document.get("title"));
System.out.println(document.get("content"));
}
client.close();
}
查询后分页
private void search(QueryBuilder queryBuilder) throws Exception {
SearchResponse searchResponse = client.prepareSearch("blog2")
.setTypes("article")
.setQuery(queryBuilder)
.setFrom(0)
.setSize(5)
.get();
SearchHits searchHits = searchResponse.getHits();
System.out.println("查询结果总记录数:" + searchHits.getTotalHits());
Iterator<SearchHit> iterator = searchHits.iterator();
while(iterator.hasNext()) {
SearchHit searchHit = iterator.next();
System.out.println(searchHit.getSourceAsString());
System.out.println("-----------?档的属性");
Map<String, Object> document = searchHit.getSource();
System.out.println(document.get("id"));
System.out.println(document.get("title"));
System.out.println(document.get("content"));
}
client.close();
}
使用文档id查询
@Test
public void testSearchById() throws Exception {
QueryBuilder queryBuilder = QueryBuilders.idsQuery().addIds("2", "3");
search(queryBuilder);
}
查询结果高亮操作
比如在京东商城搜索“笔记本” 通过开发者?具查看?亮数据的html代码实现: ElasticSearch可以对查询出的内容中关键字部分进?标签和样式的设置,但是你需要告诉ElasticSearch 使?什么标签对?亮关键字进?包裹
代码实现如下:
@Test
public void highlightSearchTest() throws Exception {
QueryBuilder queryBuilder = QueryBuilders.multiMatchQuery("桂林", "title", "content");
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("title").field("content");
highlightBuilder.preTags("<em>");
highlightBuilder.postTags("</em>");
SearchResponse searchResponse = client.prepareSearch("blog2")
.setTypes("article")
.setQuery(queryBuilder)
.highlighter(highlightBuilder)
.get();
SearchHits searchHits = searchResponse.getHits();
System.out.println("查询结果总记录数:" + searchHits.getTotalHits());
Iterator<SearchHit> iterator = searchHits.iterator();
while(iterator.hasNext()) {
SearchHit searchHit = iterator.next();
System.out.println("-----------?档的属性-----------");
Map<String, Object> document = searchHit.getSource();
System.out.println(document.get("id"));
System.out.println(document.get("title"));
System.out.println(document.get("content"));
System.out.println("************高亮结果************");
Map<String, HighlightField> highlightFields =
searchHit.getHighlightFields();
if (highlightFields.size() <=0) continue;
for (Map.Entry<String, HighlightField> entry :
highlightFields.entrySet()) {
System.out.println(entry.getKey() + ":\t" +
Arrays.toString(entry.getValue().getFragments()));
}
}
client.close();
}
查询结果如下
|