elasticsearch6.3.2学习记录二 《spring boot 搭建es开发环境,创建索引,添加数据,查询检索》

spring boot + maven + idea jdk1.8以上 搭建
一、
pom.xml文件 ,如果不需要连接数据库,可以不引入数据库连接依赖,在程序入口类加上这句注解
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})


<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.0modelVersion>

    <groupId>ag.com.esgroupId>
    <artifactId>ag-com-esartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>jarpackaging>
    <description>elasticsearch project for Spring Bootdescription>


    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.0.1.RELEASEversion>
        <relativePath/> 
    parent>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <java.version>1.8java.version>
    properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-elasticsearchartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>net.sf.json-libgroupId>
            <artifactId>json-libartifactId>
            <version>2.4version>
            <classifier>jdk15classifier>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.6.1version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.6.1version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        
        <dependency>
            <groupId>oracle-java-jdbc-coregroupId>
            <artifactId>oracle-java-jdbc-coreartifactId>
            <version>1.0version>
        dependency>

    dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <fork>truefork>
                configuration>
            plugin>
        plugins>
    build>
project>

二、创建一个controller类
1、创建索引 创建索引地址官网文档https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs.html

创建索引代码:

//获取客户端
 /**
     * 获取客户端
     * @return
     */
    public static TransportClient getClient() {
        try {
            TransportClient client;
            Settings esSettings = Settings.builder()
                    .put("cluster.name", "elasticsearch") //设置ES实例的名称
                    .put("client.transport.sniff", true) //自动嗅探整个集群的状态,把集群中其他ES节点的ip添加到本地的客户端列表中
                    .put("client.transport.ignore_cluster_name", true)  //如果集群名不对,也能连接
                    .build();
            client = new PreBuiltTransportClient(esSettings);//初始化client较老版本发生了变化,此方法有几个重载方法,初始化插件等。
            //此步骤添加IP,至少一个,其实一个就够了,因为添加了自动嗅探配置
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
            return client;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
//创建索引结构
//一、普通创建方式
IndexResponse response = client.prepareIndex("twitter", "tweet").get();
RestStatus status = response.status();//创建情况
//二、涉及到地理位置坐标系搜索的索引创建方式
client.admin().indices().prepareCreate(indexName).execute().actionGet();
            //创建索引结构
            XContentBuilder builder = null;
            builder = XContentFactory.jsonBuilder()
                    .startObject()
                        .startObject(typeName)
                            .startObject("properties")
                                .startObject("pin")
                                    .startObject("properties")
                                        .startObject("location")
                                            .field("type","geo_point")
                                        .endObject()
                                    .endObject()
                                .endObject()
                            .endObject()
                        .endObject()
                    .endObject();
            PutMappingRequest mapping = Requests.putMappingRequest(indexName).type(typeName).source(builder);
            getClient().admin().indices().putMapping(mapping).actionGet();


2、添加数据即初始化索引

//注意,你也可以索引你的文件为JSON字符串,你不必给一个ID:
IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
        .setSource(jsonBuilder()
                    .startObject()
                        .field("user", "kimchy")
                        .field("postDate", new Date())
                        .field("message", "trying out Elasticsearch")
                    .endObject()
                  )
        .get();

//使用MapinfoMap = new HashMap<>();方式
MapinfoMap = new HashMap<>()
infoMap.put("key1","value1");
infoMap.put("key2","value2");
IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
        .setSource(infoMap)
        .get();

3、查询数据

 client = EsUtil.getClient();
            SearchResponse searchResponse = client.prepareSearch("twitter")
                    .setTypes("tweet")
                    .setSize(20)//返回条数 默认十条
                    //指定匹配字段  fildNames  要匹配的字段名称用多个用逗号隔开
                    .setQuery(QueryBuilders.multiMatchQuery(keyWord, fildNames))
                    //所用字段
                    //.setQuery(new QueryStringQueryBuilder(keyword))
                    .get();
            long totalHits1 = searchResponse.getHits().totalHits;//命中个数
            SearchHit[] searchHits = searchResponse.getHits().getHits(); //执行检索
            List result = new ArrayList();
            for (int i = 0; i < searchHits.length; i++) {
                String sourceAsString = searchHits[i].getSourceAsString();
                result.add(JSONObject.fromObject(sourceAsString));
            }
            return result.toString();

你可能感兴趣的:(ES)