Very simple addition, deletion, modification and query of elastic search

Steps are as follows

1 Maven for jar package management

pom file

 <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </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.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.24</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-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>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>
        <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>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>2.0.5.RELEASE</version>
        </dependency>
    </dependencies>

2 configure applicationContext.xml of springData

(1) Client: name of es cluster, node included in es cluster

(2) Package scanner: scan the defined interface, use the interface to call the add, delete, modify and query methods provided by springData

(3) Template object: springData provides templates for es operations

<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
                          ">
    <!--Client object-->
    <elasticsearch:transport-client id="esClient" cluster-name="my-elasticsearch"
                                    cluster-nodes="127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303"/>
    <!--Packet scanner-->
    <elasticsearch:repositories base-package="com.itheima.repositories"/>
    <!--Template object-->
    <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="esClient"></constructor-arg>
    </bean>
</beans>

3. Definition document

Including index library, mapping, document, domain

@Document(indexName = "sdes_blog", type = "article")
public class Article {
    @Id
    private long id;
    @Field(type = FieldType.Long, store = true)
    private String aid;
    @Field(type = FieldType.text, store = true, analyzer = "ik_smart")
    private String title;
    @Field(type = FieldType.text, store = true, analyzer = "ik_smart")
    private String content;

4 define interface

The interface can be scanned without any annotations because it inherits from the elastic search repository

public interface ArticleRespository extends ElasticsearchRepository<Article, Long> {
}

5 add, delete, modify and query

Using the test method provided by Spring, you need to inject interface proxy object and template object

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringDataElasticSearchTest {
    @Autowired
    private ArticleRespository articleRespository;
    @Autowired
    private ElasticsearchTemplate template;

(1) Create index library

 public void createIndex() throws Exception {
        template.createIndex(Article.class);
    }

(2) Insert record

    public void addDocument() throws Exception {
        for (int i = 10; i < 20; i++) {
            Article article = new Article();
            article.setId(i);
            article.setAid("0" + i);
            article.setTitle("Why did he cut himself after 200 job cuts? Internet HR Expose the inside of layoff");
            article.setContent("From an Internet company in Shanghai HR Kevin, after cutting two hundred people, he also cut himself.");
            articleRespository.save(article);
        }

    }

See

(3) delete records

   public void deleteDocumentById() throws Exception {
        articleRespository.deleteById(1l);
    }

(4) Modification record

The modification is to delete before adding

    public void updateDocumentById() throws Exception {
        Article article = new Article();
        article.setId(0);
        article.setAid("01");
        article.setTitle("Amendment No." + article.getAid() + "Bar record");
        article.setContent("Amendment No." + article.getAid() + "Contents of records");
        articleRespository.save(article);
    }

(5) Query record

    //Query all
    public void findAll() throws Exception {
        Iterable<Article> articles = articleRespository.findAll();
        articles.forEach(article -> System.out.println(article));
    }

    //Query by id
    public void findById() throws Exception {
        Optional<Article> optional = articleRespository.findById(1l);
        Article article = optional.get();
        System.out.println(article);
    }

(6) Custom query

It is completely written in the form of springData without any extra code

public interface ArticleRespository extends ElasticsearchRepository<Article, Long> {
    List<Article> findByTitle(String title);
    List<Article> findByTitleOrContent(String title,String content);
    List<Article> findByTitleOrContent(String title, String content, Pageable pageable);
}
    //Query by title
    public void findByTitle() throws Exception {
        List<Article> list = articleRespository.findByTitle("Sanction");
        list.stream().forEach(article -> System.out.println(article));
    }

    //Queries with paging
    public void findByTitleOrContent() throws Exception {
        PageRequest pageable = PageRequest.of(0, 20);
        List<Article> list = articleRespository.findByTitleOrContent("Sanction", "Internet companies", pageable);
        list.stream().forEach(article -> System.out.println(article));
    }

(7) Native Query

Using a custom query, the query statements are in the form of and and are ordered. Use the following custom query. Although it contains keywords, no results can be found. Because it is not in the same order as the words in the index library.

    public void findByTitle() throws Exception {
        List<Article> list = articleRespository.findByTitle("Iran is sanctioned by the United States");
        list.stream().forEach(article -> System.out.println(article));
    }

With native queries, the order of words can be inconsistent.

    public void testNativeSearchQuery() throws Exception {
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.queryStringQuery("Iran is sanctioned by the United States").defaultField("title"))
                .withPageable(PageRequest.of(0, 5))
                .build();
        List<Article> list = template.queryForList(query, Article.class);
        list.stream().forEach(article -> System.out.println(article));
    }

 

138 original articles published, 89 praised, 130000 visitors+
Private letter follow

Keywords: ElasticSearch Spring Maven log4j

Added by ocd on Mon, 13 Jan 2020 13:26:54 +0200