1 springboot整合elasticsearch入门例子

记录一下最入门的例子。

一:安装elasticsearch。

在mac上很简单,brew install elasticsearch。安装完成后启动,brew services start ElasticSearch就可以了。然后访问http://localhost:9200/,出现一个json串的界面就OK了。9200是http的端口,9300是给java用户的端口。
如果是linux,看看这篇http://blog.csdn.net/cwenao/article/details/54943505,包括修改cluster.name和network.host的作用。如果不修改cluster.name那么系统是有默认的值,在第三步设置application.yml时可以看到。如果是配置远程elasticsearch集群,则设置cluster.nodes为远程的地址。
这里我们什么都不改,默认就是本机。

二:新建spring boot的elasticsearch项目。

用idea新建,勾选web和nosql里的elasticsearch选项,等待创建完成即可。
起初我用spring boot1.5.3创建的,运行时死活报一个类找不到,后改用最新的2.0.0创建的就好了。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>testelasticaearch</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>testelasticaearch</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.M1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>net.java.dev.jna</groupId>
            <artifactId>jna</artifactId>
            <version>3.0.9</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>


</project>

除了net.java.dev.jna那个是新加的,别的都是项目勾选elasticsearch后自动创建的,新加的这个依赖是因为启动后也是报类不存在,后来在网上找个jna依赖加上后就好了。

三:配置yml文件。

spring:
   data:
        elasticsearch:
            #cluster-name: #默认为elasticsearch
            #cluster-nodes: 127.0.0.1: #配置es节点信息,逗号分隔,如果没有指定,则启动ClientNode
            properties:
                path:
                  logs: ./elasticsearch/log #elasticsearch日志存储目录
                  data: ./elasticsearch/data #elasticsearch数据存储目录

四:创建javaBean文件。

我直接用http://www.tianshouzhi.com/api/tutorials/springboot/101这篇文章里的类。
把Author类和Tutorial类复制过来,还有Article类。简单说一下Article类。

package com.example.demo.pojo;

import org.springframework.data.elasticsearch.annotations.Document;

import java.io.Serializable;
import java.util.Date;

/**
 * Created by admin on 17/6/1.
 */
@Document(indexName="projectname",type="article",indexStoreType="fs",shards=5,replicas=1,refreshInterval="-1")
public class Article implements Serializable {
    @Id
    private Long id;
    /**标题*/
    private String title;
    /**摘要*/
    private String abstracts;
    /**内容*/
    private String content;
    /**发表时间*/
    private Date postTime;
    /**点击率*/
    private Long clickCount;
    /**作者*/
    private Author author;
    /**所属教程*/
    private Tutorial tutorial;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAbstracts() {
        return abstracts;
    }

    public void setAbstracts(String abstracts) {
        this.abstracts = abstracts;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getPostTime() {
        return postTime;
    }

    public void setPostTime(Date postTime) {
        this.postTime = postTime;
    }

    public Long getClickCount() {
        return clickCount;
    }

    public void setClickCount(Long clickCount) {
        this.clickCount = clickCount;
    }

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }

    public Tutorial getTutorial() {
        return tutorial;
    }

    public void setTutorial(Tutorial tutorial) {
        this.tutorial = tutorial;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", abstracts='" + abstracts + '\'' +
                ", content='" + content + '\'' +
                ", postTime=" + postTime +
                ", clickCount=" + clickCount +
                ", author=" + author +
                ", tutorial=" + tutorial +
                '}';
    }
}

@Document注解里面的几个属性,类比mysql的话是这样:
index –> DB
type –> Table
Document –> row
@Id注解加上后,在Elasticsearch里相应于该列就是主键了,在查询时就可以直接用主键查询,后面一篇会讲到。其实和mysql非常类似,基本就是一个数据库。

@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Document {

String indexName();//索引库的名称,个人建议以项目的名称命名

String type() default "";//类型,个人建议以实体的名称命名

short shards() default 5;//默认分区数

short replicas() default 1;//每个分区默认的备份数

String refreshInterval() default "1s";//刷新间隔

String indexStoreType() default "fs";//索引文件存储类型
}

加上了@Document注解之后,默认情况下这个实体中所有的属性都会被建立索引、并且分词。
我们通过@Field注解来进行详细的指定,如果没有特殊需求,那么只需要添加@Document即可。

@Field注解的定义如下:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Inherited
public @interface Field {

FieldType type() default FieldType.Auto;#自动检测属性的类型

FieldIndex index() default FieldIndex.analyzed;#默认情况下分词

DateFormat format() default DateFormat.none;

String pattern() default "";

boolean store() default false;#默认情况下不存储原文

String searchAnalyzer() default "";#指定字段搜索时使用的分词器

String indexAnalyzer() default "";#指定字段建立索引时指定的分词器

String[] ignoreFields() default {};#如果某个字段需要被忽略

boolean includeInParent() default false;
}

五:dao和controller

Dao:

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

controller:

package com.example.demo;

import com.example.demo.pojo.Article;
import com.example.demo.pojo.Author;
import com.example.demo.pojo.Tutorial;
import com.example.demo.repository.ArticleSearchRepository;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Iterator;

/**
 * Created by admin on 17/6/1.
 */
@RestController
public class TestController {
    @Autowired
    private ArticleSearchRepository articleSearchRepository;

    @RequestMapping("/add")
    public void testSaveArticleIndex() {
        Author author = new Author();
        author.setId(1L);
        author.setName("tianshouzhi");
        author.setRemark("java developer");

        Tutorial tutorial = new Tutorial();
        tutorial.setId(1L);
        tutorial.setName("elastic search");

        Article article = new Article();
        article.setId(1L);
        article.setTitle("springboot integreate elasticsearch");
        article.setAbstracts("springboot integreate elasticsearch is very easy");
        article.setTutorial(tutorial);
        article.setAuthor(author);
        article.setContent("elasticsearch based on lucene,"
                + "spring-data-elastichsearch based on elaticsearch"
                + ",this tutorial tell you how to integrete springboot with spring-data-elasticsearch");
        article.setPostTime(new Date());
        article.setClickCount(1L);

        articleSearchRepository.save(article);
    }

    @RequestMapping("/query")
    public void testSearch() {
        String queryString = "springboot";//搜索关键字
        QueryStringQueryBuilder builder = new QueryStringQueryBuilder(queryString);
        Iterable<Article> searchResult = articleSearchRepository.search(builder);
        Iterator<Article> iterator = searchResult.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

启动项目,先执行add,往elasticsearch添加一条数据,然后再访问query即可看到结果了。
其实非常类似于普通的DB查询,还支持很多条件查询,findAll,findTop之类的,就是JPA那一套可以直接用,因为继承的ElasticsearchRepository本身就是一个PagingAndSortingRepository。
参考:http://www.cnblogs.com/softidea/p/6102796.html

好的,我可以为您提供相关的信息和代码示例。首先,您需要确保您的Spring Boot项目中包含以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.0.0</version> </dependency> ``` 接下来,您需要在application.properties文件中添加以下配置: ```properties spring.data.elasticsearch.cluster-name=my-application spring.data.elasticsearch.cluster-nodes=localhost:9300 ``` 然后,您可以编写Elasticsearch工具类来执行一些常见的操作,例如索引文档、搜索文档等。以下是一个示例工具类: ```java import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.Map; @Component public class ElasticsearchUtil { @Autowired private RestHighLevelClient restHighLevelClient; /** * 索引文档 * @param indexName 索引名称 * @param id 文档ID * @param sourceMap 文档内容 * @throws IOException */ public void indexDocument(String indexName, String id, Map<String, Object> sourceMap) throws IOException { IndexRequest request = new IndexRequest(indexName); if (id != null) { request.id(id); } request.source(sourceMap); restHighLevelClient.index(request, RequestOptions.DEFAULT); } /** * 更新文档 * @param indexName 索引名称 * @param id 文档ID * @param sourceMap 文档内容 * @throws IOException */ public void updateDocument(String indexName, String id, Map<String, Object> sourceMap) throws IOException { UpdateRequest request = new UpdateRequest(indexName, id); request.doc(sourceMap); restHighLevelClient.update(request, RequestOptions.DEFAULT); } /** * 批量索引文档 * @param indexName 索引名称 * @param sourceMaps 文档内容列表 * @throws IOException */ public void bulkIndexDocuments(String indexName, Map<String, Object>[] sourceMaps) throws IOException { BulkRequest request = new BulkRequest(); for (Map<String, Object> sourceMap : sourceMaps) { IndexRequest indexRequest = new IndexRequest(indexName); indexRequest.source(sourceMap); request.add(indexRequest); } restHighLevelClient.bulk(request, RequestOptions.DEFAULT); } /** * 批量更新文档 * @param indexName 索引名称 * @param idList 文档ID列表 * @param sourceMap 文档内容 * @throws IOException */ public void bulkUpdateDocuments(String indexName, String[] idList, Map<String, Object> sourceMap) throws IOException { BulkRequest request = new BulkRequest(); for (String id : idList) { UpdateRequest updateRequest = new UpdateRequest(indexName, id); updateRequest.doc(sourceMap); request.add(updateRequest); } restHighLevelClient.bulk(request, RequestOptions.DEFAULT); } /** * 获取文档 * @param indexName 索引名称 * @param id 文档ID * @return * @throws IOException */ public Map<String, Object> getDocument(String indexName, String id) throws IOException { GetRequest request = new GetRequest(indexName, id); return restHighLevelClient.get(request, RequestOptions.DEFAULT).getSourceAsMap(); } /** * 搜索文档 * @param indexName 索引名称 * @param keyword 关键词 * @param size 每页数量 * @param from 起始位置 * @return * @throws IOException */ public SearchHits searchDocuments(String indexName, String keyword, int size, int from) throws IOException { SearchRequest searchRequest = new SearchRequest(indexName); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchQuery("content", keyword)); searchSourceBuilder.from(from); searchSourceBuilder.size(size); searchSourceBuilder.timeout(TimeValue.timeValueSeconds(60)); searchRequest.source(searchSourceBuilder); SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT); return searchResponse.getHits(); } } ``` 最后,您可以在您的代码中使用ElasticsearchUtil类,并根据您的需求调用它的方法来执行所需的操作。以下是一个示例调用: ```java import org.elasticsearch.search.SearchHits; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.HashMap; import java.util.Map; @RestController public class DemoController { @Autowired private ElasticsearchUtil elasticsearchUtil; @GetMapping("/index") public String index() throws IOException { Map<String, Object> sourceMap = new HashMap<>(); sourceMap.put("title", "Elasticsearch 7 教程"); sourceMap.put("content", "Elasticsearch 7 入门教程"); elasticsearchUtil.indexDocument("my_index", null, sourceMap); return "索引文档成功!"; } @GetMapping("/search") public String search(@RequestParam("keyword") String keyword, @RequestParam("size") int size, @RequestParam("from") int from) throws IOException { SearchHits searchHits = elasticsearchUtil.searchDocuments("my_index", keyword, size, from); return searchHits.toString(); } } ``` 希望这些代码示例可以帮助您整合Elasticsearch 7到您的Spring Boot项目中,并提供了一些常见的操作示例。
评论 30
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天涯泪小武

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值