public void elastic() throws Exception{
//创建搜索服务器对象
Client client = TransportClient
.builder()
.build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9300 ));
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.field("id","1")
.field("title","elasticsearch的入门案列")
.field("context","ElasticSearch是一个基于Lucene的搜索服务器。"
+ "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。")
.endObject();
//创建文档对象
client.prepareIndex("blog1", "article", "1").setSource(builder).get();
//关闭连接
client.close();
}
@Test
public void sechar() throws Exception{
//创建连接
Client client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.01"), 9300));
//搜索数据
SearchResponse searchResponse = client.prepareSearch("blog1")
.setTypes("article")
.setQuery(QueryBuilders.matchAllQuery()).get(); //查询所有
SearchHits hits = searchResponse.getHits();
System.out.println("查询数据的条数" + hits.getTotalHits());
Iterator<SearchHit> iterator = hits.iterator();
while (iterator.hasNext()) {
SearchHit next = iterator.next();
System.out.println(next.getSourceAsString());
System.out.println("title:" + next.getSource().get("title"));
}
// 关闭client
client.close();
}
//默认分词机制
@Test
public void sechar1() throws Exception{
//创建连接
Client client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.01"), 9300));
//搜索数据
SearchResponse searchResponse = client.prepareSearch("blog1")
.setTypes("article")
.setQuery(QueryBuilders.queryStringQuery("程全")).get(); //默认分词机制 全 ,程 单个词
searchSelect(client, searchResponse);
}
//模糊查询
@Test
public void sechar2() throws Exception{
//创建连接
Client client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.01"), 9300));
//搜索数据
SearchResponse searchResponse = client.prepareSearch("blog1")
.setTypes("article")
.setQuery(QueryBuilders.wildcardQuery("context", "*程全*")).get(); //查询不到 说明词条中没有 程全
searchSelect(client, searchResponse);
}
//termQuery 词条查询
@Test
public void sechar3() throws Exception{
//创建连接
Client client = TransportClient.builder().build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.01"), 9300));
//搜索数据
SearchResponse searchResponse = client.prepareSearch("blog1")
.setTypes("article")
.setQuery(QueryBuilders.termQuery("context", "全")).get(); //查询不到 说明词条中没有 程全
searchSelect(client, searchResponse);
}