欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ElasticSearch(二)

程序员文章站 2022-03-05 09:56:29
...

Elasticsearch

使用原生API操作elasticsearch
在pom.xml中导入坐标
<properties>
    <maven.compiler.target>1.9</maven.compiler.target>
    <maven.compiler.source>1.9</maven.compiler.source>
</properties>
<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>
      <!--jackson依赖-->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.1</version>
    </dependency>
</dependencies>
创建索引库index
@Test
public void testCreateIndex()throws UnknownHostException{
	//创建Settings对象,相当于配置信息
	Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();
	//创建TrasnportClient对象,TransportClient是一个abstract类
	TransportClient client = new PreBuiltTransportClient(settings);
	//指定本机IP地址,Inet协议端口号
	client.addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9300));
	//创建索引库
	client.admin().indices().prepareCreate("blog").get();
	//释放资源
	client.close();
}
创建索引库后设置mapping
@Test
public void testSetMapping(){
	//创建Settings对象,相当于配置信息
	Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();
	//创建TrasnportClient对象
	TransportClient client = new PreBuiltTransportClient(settings);
	//指定本机IP地址,Inet协议端口号
	client.addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9300));
	//获取XContentBuilder对象
	XContentBuilder builder = XContentFactory.jsonBuilder()
		.startObject()
			.startObject("article")		
				.startObject("properties")
					.startObject("id")
						.field("type","long")
						.field("store",true)
						.field("index",true)
					.endObject()
					.startObject("title")
						.field("type","text")
						.field("store",true)
						.field("index",true)
						.field("analyzer","ik_smart")
					.endObject()
					.startObject("content")
						.field("type","text")
						.field("store",true)
						.field("index",true)
						.field("analyzer","ik_smart")	
					.endObject()
				.endObject()
			.endObject()
		.endObject();
//获取PutMappingRequest对象
PutMappingRequest mapping = Requests.putRequestMapping("blog")
		.type("article")
		.source(builder);
//执行设置mapping
client.admin().indices().putMapping(mapping).get();
//释放资源
client.close();
}
抽取获得Client对象和释放资源的方法
private TransportClient client;
@Before
public void init(){
	Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();
	client = new PreBuiltTransportClient(settings);
	client.addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9300));
}
@After
public void destroy(){
	client.close();
}
添加一条Document
<!--使用XContentBuilder来保存一条Document-->
@Test
public void testSaveDocumentByXContentBuilder(){
	//获取XContentBuilder对象
	XContentBuilder builder = XContentFactory.jsonBuilder()
		.startObject()
			.field("id",1l)
			.field("title","test title one")
			.field("content","test content one")
		.endObject();
	//执行添加操作
	client.prepareIndex("blog","article","1").setSource(builder).get();
}
<!--使用Jackson转换实体类数据后保存-->
public class Article{
	private long id;	
	private String title;
	private String content;
}
@Test
public void testSaveDocumentByJackson(){
	//创建Article对象
	Article article = new Article(2l,"test title two","test content two");
	//将article对象转换为json字符串
	String articleStr = new ObjectMapper().writeValueAsString(article);
	//执行添加操作
	client.prepareIndex("blog","article",article.getId().toString())
.setSource(articleStr,XContentType.JSON).get();
}
查询Documents
1.根据文档ID查询
@Test
public void testFindById(){
	//创建QueryBuilder对象
	QueryBuilder builder = QueryBuilders.idsQuery().addIds("1","2");
	search(builder);
}
2.根据关键词(Term)查询
@Test
public void testFindByTerm(){
	//创建QueryBuilder对象
	QueryBuilder builder = QueryBuilders.termQuery("content","test");
	search(builder);
}
3.根据QueryString(分词)查询
@Test
public void testFindByString(){
	//创建QueryBuilder对象
QueryBuilder builder = QueryBuilders.queryStringQuery("content","test").defaultField("content");
	search(builder);
}
 
private void search(QueryBuilder builder){
	//获取SearchResponse对象
	SearchResponse search = client.prepareSearch("blog")
								.setTypes("article")
								.setQuery(builder)
								.get();
	//获取SearchHits对象
	SearchHits searchHits = search.getHits();
	System.out.println("总记录数:"+searchHits.getTotalHits());
	//迭代searchHits集合
	Iterator<SearchHit> it = searchHits.iterator();
     while(it.hasNext()){
        String document = it.next().getSourceAsString();
    }
}
分页查询
	SearchResponse search = SearchResponse.prepareSearch("blog")
								.setType("article")
								.setQuery(builder)	
								.setFrom(0)		//from:设置起始的行号,从0开始
								.setSize(15)	//size:设置每页显示的记录数,默认是10条记录
								.get();
Highlight Show
	//创建HighlightBuilder对象
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    highlightBuilder.preTags("<font style='color:red'>");	//设置关键字的前缀
    highlightBuilder.postTags("</fontfont>");		//设置关键字的后缀
    highlightBuilder.field("title");		 //设置高亮显示的域
SearchResponse search = SearchResponse.prepareSearch("blog")
								.setType("article")
								.setQuery(builder)	
								.setFrom(0)		 
								.setSize(15)
								.highlighter(highlightBuilder)
								.get();
	Iterator<SearchHit> it = searchHits.iterator();
     while(it.hasNext()){
        SearchHit searchHit = it.next();
        System.out.println("String方式打印文档搜索内容:");
        System.out.println(searchHit.getSourceAsString());
        System.out.println("Map方式打印高亮内容");
        System.out.println(searchHit.getHighlightFields());
        System.out.println("遍历高亮集合,打印高亮片段:");
        Text[] text = searchHit.getHighlightFields().get("title").getFragments();
        for (Text str : text) {
            System.out.println(str);
        }
    }
相关标签: elasticsearch