3.使用Spring Data ElasticSearch操做ElasticSearch(5.6.8版本)

1.引入maven座標java

<!--spring-data-elasticsearch-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>3.0.5.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--elasticsearch-->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.8</version>
</dependency>
<!--transport-->
<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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
<!--json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<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>

2.配置ElasticSearchnode

<?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.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/data/elasticsearch
		http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
		">
    <!-- 配置elasticSearch客戶端的鏈接 -->
    <elasticsearch:transport-client id="client" cluster-nodes="localhost:9301,localhost:9302,localhost:9303" cluster-name="my-application"/>
    <!-- 掃描Dao包,自動建立實例 -->
    <elasticsearch:repositories base-package="com.caizhen.springdata.elasticsearch.dao"/>
    <!-- 掃描Service包,建立Service的實體 -->
    <context:component-scan base-package="com.caizhen.springdata.elasticsearch.service"/>
    <!-- ElasticSearch模版對象 -->
    <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <constructor-arg name="client" ref="client"></constructor-arg> </bean>

</beans>

3.配置daoweb

@Repository
public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> {

}

4.配置servicespring

@Service public class ArticleServiceImpl implements ArticleService {  

@Autowired

private ArticleRepository articleRepository;
@Autowired private ElasticsearchTemplate elasticsearchTemplate; //新建索引 public void creatIndex() { //建立索引,並配置映射關係 elasticsearchTemplate.createIndex(Article.class);
//建立映射關係 // elasticsearchTemplate.putMapping(Article.class); } //保存文檔 public void save(Article article) { articleRepository.save(article); }
//更新文檔,ealasticsearch根據id判斷該數據是否存在若存在則進行修改
@Test
    public void update(){
        Article article = new Article();
        article.setId(1001);
        article.setTitle("elasticSearch 3.0版本發佈...更新");
        article.setContent("ElasticSearch是一個基於Lucene的搜索服務器。它提供了一個分佈式多用戶能力的全文搜索引擎,基於RESTful web接口");
        articleService.save(article);
    }
//刪除文檔
  public void delete(){
        Article article = new Article();
        article.setId(1001);
        articleService.delete(article);
    }
//分頁查詢
    @Test
    public void findAllPage(){
        Pageable pageable = PageRequest.of(1,10);//page,pagesize,初始頁是從0開始
        Page<Article> page = articleService.findAll(pageable);
        for(Article article:page.getContent()){
            System.out.println(article);
        }
    }

}

3.3.2 經常使用查詢命名規則apache

關鍵字 命名規則 解釋 示例
and findByField1AndField2 根據Field1和Field2得到數據 findByTitleAndContent
or findByField1OrField2 根據Field1或Field2得到數據 findByTitleOrContent
is findByField 根據Field得到數據  findByTitle  
not findByFieldNot 根據Field得到補集數據 findByTitleNot
between findByFieldBetween 得到指定範圍的數據 findByPriceBetween
lessThanEqual findByFieldLessThan 得到小於等於指定值的數據 findByPriceLessThan

 3.3.3 查詢方法測試json

1)dao層實現api

public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> {
    //根據標題查詢
    List<Article> findByTitle(String condition);
    //根據標題查詢(含分頁)
    Page<Article> findByTitle(String condition, Pageable pageable);
}

2)service實現服務器

public interface ArticleService {
    //根據標題查詢
    List<Article> findByTitle(String condition);
    //根據標題查詢(含分頁)
    Page<Article> findByTitle(String condition, Pageable pageable);
}

3)service層實現app

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    public List<Article> findByTitle(String condition) { return articleRepository.findByTitle(condition); }
    public Page<Article> findByTitle(String condition, Pageable pageable) { return articleRepository.findByTitle(condition,pageable); }

}

4)單元測試less

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringDataESTest {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private TransportClient client;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate; 
    /**條件查詢*/
    @Test
    public void findByTitle(){
        String condition = "版本";
        List<Article> articleList = articleService.findByTitle(condition);
        for(Article article:articleList){
            System.out.println(article);
        }
    }

    /**條件分頁查詢*/
    @Test
    public void findByTitlePage(){
        String condition = "版本";
        Pageable pageable = PageRequest.of(2,10);
       Page<Article> page = articleService.findByTitle(condition,pageable);
        for(Article article:page.getContent()){
            System.out.println(article);
        }
    }
    /**條件分頁查詢*/
    @Test
    public void findByTitlePage(){
        String condition = "版本";
        Pageable pageable = PageRequest.of(2,10);
        Page<Article> page = articleService.findByTitle(condition,pageable);
        for(Article article:page.getContent()){
            System.out.println(article);
        }
    } }

 

5)使用Elasticsearch的原生查詢對象進行查詢。

@Test
    public void findByNativeQuery() {
        //建立一個SearchQuery對象
      SearchQuery searchQuery = new NativeSearchQueryBuilder()
                //設置查詢條件,此處能夠使用QueryBuilders建立多種查詢 .withQuery(QueryBuilders.queryStringQuery("SpringData").defaultField("title"))
                //還能夠設置分頁信息
                .withPageable(PageRequest.of(0, 5))
                //建立SearchQuery對象
                .build();
        //使用模板對象執行查詢
        List<Article> articleList= elasticsearchTemplate.queryForList(searchQuery, Article.class);
        for(Article list: articleList){ System.out.println(list); }
    }

6)總結 

自定義方法能夠對搜索的內容先分詞再進行查詢,每一個詞之間條件都是and的關係,一個詞分詞後的片斷必須都同時知足

原生方法是or的關係

相關文章
相關標籤/搜索