Spring data elastic search uses

Keywords: Java Spring ElasticSearch JSON

I installed elastic search a long time ago, but I haven't used it in java. Recently, I read the spring data series of elastic search. Here is my experience.

If you haven't installed elastic search, you can refer to it https://www.cnblogs.com/shaozm/p/8732842.html This article.

I. Primitive Writing

Connect client

First, talk about the original writing.

 private TransportClient client;
    public TransportClient getClient(){
        Settings setting = Settings.builder()
                .put("cluster.name", "elas_cluster")
                .put("client.transport.ignore_cluster_name", true)
//                    .put("client.transport.nodes_sampler_interval", 5) //
                .put("client.transport.sniff", true)
                .build();

        client = new PreBuiltTransportClient(setting)
                .addTransportAddress(
                        new TransportAddress(new InetSocketAddress("192.168.0.2",9300))
                );
        return  client;

    }

First connect to the client, where the single node and the cluster write the same way, if it is a cluster, only need to configure the master node. Officially, after the client opens sniffing, the list of sniffing nodes will be overwritten locally.

 

search

Because I use spring data elastic search framework to import data, so I don't write index, type creation, just show you how to write the search.  

 public  void  search(){

        QueryBuilder queryBuilder= QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("newsTitle","First Business Club"))
                .must(QueryBuilders.matchQuery("newsCate","science and technology"));

        SearchResponse response= client.prepareSearch("test")
                .setTypes("newsArticle")
                .setQuery(queryBuilder).get();
        SearchHits searchHits = response.getHits();
        for(SearchHit searchHit : searchHits) {
            System.out.println(searchHit);
        }

        client.close();
    }

 

Basic Search Resolution

Let's start with the basic search.

The search request of elastic search is restful, and its search request is searched according to the parameters of json format.

In general, the general search json of elastic search is similar to {"query":...}.

Firstly, all the searches of elastic search are basically divided into two kinds, one is filtering, the other is query (in order to distinguish me from scoring search), and they are illustrated by examples.

For example, filter search judgments are not consistent with direct judgments, such as whether it is in this age range, whether the field matches, whether it is returned, not not not not not returned,?

Score search has a score as a basis for returning, such as this field matches, give you a score, that field does not match, no score, comprehensive all the scores to see whether it is up to the standard, up to the standard returned, not up to the standard did not return.

Similar

 { "query" : {"range" : { ....... }} }

{"query": {term": {term": {......}} Term is an exact query that needs to be matched perfectly

Belong to filter search

{ "query" : {"match" : { ....... }} }

 { "query" : {"bool" : { ....... }} }

Belonging to Score Search

For example, {"query": {"bool": {......}} is a combination of multiple queries, where the content of...... can be a combination of multiple musts or should s or must_not or filter s, and the final score is calculated.

2. spring data elastic search

Dead work

Now you can get into the topic, the usage of spring data elastic search

Pilot Kit

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

Next, configure yml

spring:
data: elasticsearch: repositories: enabled:
true cluster-nodes: 192.168.0.2:9300 cluster-name: elas_cluster

 

abnormal

Here's a bug. If you have redis, you might throw an exception. I configure this line in the boot class.

public static void main(String[] args) throws Exception{
    System.setProperty("es.set.netty.runtime.available.processors", "false");
    SpringApplication.run(EsStart.class,args);
}

 

 

Detailed explanation

The framework of spring-data series, all who have used jpa should know the routine

First configure entity annotations

@Document(indexName = "test",type = "newsArticle")
public class NewsArticlePO {
 ......
}

 


If there are any fields that need a word splitter, you can configure them separately
. . . . . . 
@Field(type = FieldType.Text, analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
private String newsTitle;
. . . . . . 

 



At this point, as soon as you start the project, you will find that the index and type have been automatically generated.

The second step

Create repository

public interface ArticleRepository extends ElasticsearchRepository<NewsArticlePO,Long> {
   . . . . . . 
}

 


There are several ways to do this. One is to define new methods by using name rules, the other is to create queries with query annotations, and the other is to use parent inheritance.

The first method

Create methods in ArticleRepository
/**
* Search for two fields by title, category
* */
List<NewsArticlePO> findByNewsTitleAndAndNewsCate(String newsTitle,String newsCate);

 

Specific rules refer to the appendix to the official document of spring data elastic search

The second method
Create methods in ArticleRepository 
@Query("{\"bool\": {\"must\": [{ \"match\": { \"newsTitle\": \"?0\"}},{ \"match\": { \"newsCate\": \"?1\"}}]}}")
List<NewsArticlePO> findByQuery(String newsTitle, String newsCate);

 


The third method
Injecting ArticleRepository into service layer code or other classes
@Resource
private ArticleRepository articleRepository;


Creating method
public Page<NewsArticlePO> searchBuild(String newsTitle, String newsCate) {

    QueryBuilder queryBuilder= QueryBuilders.boolQuery()
            .must(QueryBuilders.matchQuery("newsTitle",newsTitle))
            .must(QueryBuilders.matchQuery("newsCate",newsCate));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery(queryBuilder)
            .build();
    return   articleRepository.search(searchQuery);
}

 



That's ok ay. If you don't like repository, you can inject Elastic search Template.
@Resource
private ElasticsearchTemplate elasticsearchTemplate;
public List<NewsArticlePO> searchTemplate(String newsTitle, String newsCate){
    QueryBuilder queryBuilder= QueryBuilders.boolQuery()
            .must(QueryBuilders.matchQuery("newsTitle",newsTitle))
            .must(QueryBuilders.matchQuery("newsCate",newsCate));

    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withQuery(queryBuilder)
            .build();
    return elasticsearchTemplate.queryForList(searchQuery,NewsArticlePO.class);
}

 


You can even get a native client through elastic searchTemplate. getClient () to operate on

demo project address https://github.com/1160809039/elasticsearch-demo



Posted by Braet on Thu, 16 May 2019 01:09:28 -0700