zoukankan      html  css  js  c++  java
  • Spring集成ElasticSearch

    这篇博客主要讲入门,具体实现需要看官方文档!
    Spring集成ElasticSearch:
    优点:将原生API进行封装,操作ES非常简单。
    缺点:容易造成版本冲突。

    参考资料

    spring-data-elasticsearch官网

    设置pom文件

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-elasticsearch</artifactId>
        <version>2.1.0.RELEASE</version>
    </dependency>
    		
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>2.4.5</version>
    </dependency>
    

    配置es.properties文件

    #默认即为elasticsearch
    cluster_name=elasticsearch
    #配置es节点信息,逗号分隔。
    elasticsearch_nodes=172.16.30.56:9300,172.16.30.126:9300
    

    配置elasticSearch.xml中的ElasticsearchTemplate类信息

    <?xml version="1.0" encoding="UTF-8" ?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
        xsi:schemaLocation="
    		http://www.springframework.org/schema/beans 
    		http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    		http://www.springframework.org/schema/context 
    		http://www.springframework.org/schema/context/spring-context-4.0.xsd 
            http://www.springframework.org/schema/data/elasticsearch
            http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd ">
        <context:property-placeholder location="WEB-INF/conf/es.properties" />
        <elasticsearch:repositories base-package="com.scheduleserver.repository"/>
        <elasticsearch:transport-client id="client" cluster-nodes="${elasticsearch_nodes}" cluster-name="${cluster_name}"/>
    
        <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
            <constructor-arg name="client" ref="client"/>
        </bean>
    </beans>
    

    application.xml引入上面的配置信息

    <import resource="classpath:elasticSearch.xml"/>
    

    索引对应的实体类(和文档的元数据要对应哦)

    索引:zjb,类型:note
    @Document(indexName="zjb",type="note")
    public class EsZjbNote {
    	@Id
        private String f_note_id;
    	/**
    	 * type  	可以是Boolean,Long,Double,Date,String类型。
    	 * index 	analyzed表示索引,并且对数据进行拆词;not_analyzed表示索引,但是不进行拆词;no表示不索引。
    	 * analyzer   是字段文本的分词器。默认standard分词器。
    	 * search_analyzer     是搜索词的分词器。
    	 * 设置store为true,可以把字段原始值保存,但是索引会更大,需要根据需求使用。
    	 */
    	@Field(type = FieldType.String, index = FieldIndex.not_analyzed, store= true)
    	private String f_criticalit;
    	@Field
    	private String f_start_time;
    	@Field
    	private String f_create_time;
    	@Field
    	private String f_attention;
    	@Field
    	private String f_relation;
    ......此处省略一堆setter和getter方法
    

    定义实体类对应的dao接口

    @Component
    // 因为文档的id是String类型的,所以泛型的第二个参数是String。
    public interface ZjbNoteEsRepository extends ElasticsearchRepository<EsZjbNote,String>{
    
    }
    

    查:根据Id属性查找文档

    // ES存在一个id=023dc4f1a0c9451ab6e88962f9b623ea的文档。
    EsZjbNote note = repository.findOne("023dc4f1a0c9451ab6e88962f9b623ea");
    

    查:全文检索

    QueryStringQueryBuilder builder = new QueryStringQueryBuilder(message);
    iterable = repository.search(builder);
    iterator = iterable.iterator();
    

    查:简单的布尔查询

    	@Autowired
    	private ZjbNoteEsRepository repository;
    
    	public List<ZjbNotePo> searchByEs(String message,String userId) {
    	  	Iterable<EsZjbNote> iterable;
    		Iterator<EsZjbNote> iterator;
    		List<ZjbNotePo> list = new ArrayList<>();
    		BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
    		boolQueryBuilder.must(QueryBuilders.matchQuery("f_keywords", message));
    		boolQueryBuilder.filter(QueryBuilders.termQuery("f_user_id", userId));
    		iterable = repository.search(boolQueryBuilder);
    		iterator = iterable.iterator();
    		// 遍历取值
    		while(iterator.hasNext()) {
    			EsZjbNote esNote = iterator.next();
    			ZjbNotePo note = new ZjbNotePo();
    			note.setfAttention(Integer.parseInt(esNote.getF_attention()));
    			note.setfContent(esNote.getF_content());
    			note.setfCreateTime(esNote.getF_create_time());
    			note.setfCriticalit(Integer.parseInt(esNote.getF_criticalit()));
    			note.setfKeywords(esNote.getF_keywords());
    			list.add(note);
    			........省略代码
    
    

    查:分页、权重

    // 从第0个开始,返回3个文档。
    Pageable pageable = new PageRequest(0, 3);
    //设置权重
    FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
    	.add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("f_keywords", message)),
    		ScoreFunctionBuilders.weightFactorFunction(1000))
    	.add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("f_content", message)),
    		ScoreFunctionBuilders.weightFactorFunction(100));
    //分页,权重
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(pageable)
    	.withQuery(functionScoreQueryBuilder).build();
    iterable = repository.search(searchQuery);
    iterator = iterable.iterator();
    

    增:增加或者修改都是使用save方法

    // 这个属性必须要有,它对应ES中唯一文档!
    note.setF_note_id("023dc4f1a0c9451ab6e88962f9b623ea");
    EsZjbNote note = new EsZjbNote();
    note.setF_user_id("666666");
    note.setF_content("费哥好帅啊");
    note.setF_keywords("keyword");
    note.setF_locale("中国山东济南历下区");
    //仓库接口
    repository.save(note);
    
    

    删:删除的对象必须要有标记为@Id的属性

    EsZjbNote note = new EsZjbNote();
    note.setF_note_id("023dc4f1a0c9451ab6e88962f9b623ea");
    repository.delete(note);
    
  • 相关阅读:
    用class定义类--Python
    列表推导(list comprehension)--Python
    排序--Python
    腌制数据--python(pickle标准库)
    Python--异常处理
    Python--各种杂乱的笔记
    python--文件读写
    我靠 xmind居然可以在博客园这么分享
    思维导图记录
    思维导图记录
  • 原文地址:https://www.cnblogs.com/feiqiangsheng/p/10971490.html
Copyright © 2011-2022 走看看