今天第一次使用版本5.X, 和2.X  有些区别(整体使用上区别不是很大) :

 

方式1:

maven :

<?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>org.example</groupId>
    <artifactId>SeaESDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
   <dependencies>
       <dependency>
           <groupId>org.elasticsearch</groupId>
           <artifactId>elasticsearch</artifactId>
           <version>5.6.2</version>
       </dependency>
       <dependency>
           <groupId>org.elasticsearch.client</groupId>
           <artifactId>transport</artifactId>
           <version>5.6.2</version>
       </dependency>
       <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.12</version>
           <scope>compile</scope>
       </dependency>

       <dependency>
           <groupId>org.apache.logging.log4j</groupId>
           <artifactId>log4j-core</artifactId>
           <version>2.10.0</version>
       </dependency>
       <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
       <dependency>
           <groupId>org.apache.logging.log4j</groupId>
           <artifactId>log4j-api</artifactId>
           <version>2.10.0</version>
       </dependency>
   </dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.0.1</version>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


</project>

 

 

 

 

整理下:

package com.sea.es;

import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @PACKAGE : com.sea.es
 * @Author :  Sea
 * @Date : 12/14/20 12:55 PM
 * @Desc :
 **/
public class ESTest {

    public static String CLUSTER_NAME = "es-cluster";//Elasticsearch集群名称
    public static String HOST_IP = "192.168.18.129";//Elasticsearch集群节点
    public static int TCP_PORT = 9300;//Elasticsearch节点TCP通讯端口
    private volatile static TransportClient client;//客户端对象,用于连接到Elasticsearch集群

    public static TransportClient getSingleTransportClient() {
        Settings settings  = Settings.builder().put("cluster.name", CLUSTER_NAME).build();
        try {
            if(client == null) {
                synchronized(TransportClient.class) {
                    client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST_IP), TCP_PORT));
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return client;
    }

   @Before
    public void  init(){
        TransportClient client = getSingleTransportClient();
    }

    @Test
    public void testName() throws Exception {

//        GetResponse getResponse = client.prepareGet("books", "IT", "1").get();
//        System.out.println(getResponse.getSourceAsString());
        client.admin().indices().prepareCreate("shan").get();
    }

    /**
     * 使用json来创建文档、索引、自动创建映射
     */
    @Test
    public void createDoc_1() {
        // json数据
        String source = "{" +
                "\"id\":\"3\"," +
                "\"title\":\"ElasticSearch是一个基于Lucene的搜索服务器\"," +
                "\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"" +
                "}";

        // 开始创建文档
        // .execute().actionGet() == .get()
        IndexResponse indexResponse = client.prepareIndex("blog01", "article", "3").setSource(source, XContentType.JSON).get();

        // 获取响应信息
        System.out.println("索引:" + indexResponse.getIndex());
        System.out.println("类型:" + indexResponse.getType());
        System.out.println("ID:" + indexResponse.getId());
        System.out.println("版本:" + indexResponse.getVersion());
        System.out.println("是否创建成功:" + indexResponse.status());

        client.close();
    }

    /**
     * 使用map来创建文档
     */
    @Test
    public void createDoc_2() {
        // map格式的数据
        Map<String, Object> source = new HashMap<>();
        source.put("id", "2");
        source.put("title", "我们建立一个网站或应用程序");
        source.put("content", "但是想要完成搜索工作的创建是非常困难的");

        // 创建文档
        IndexResponse indexResponse = client.prepareIndex("blog01", "article", "2").setSource(source).get();

        // 获取响应信息
        System.out.println("索引:" + indexResponse.getIndex());
        System.out.println("类型:" + indexResponse.getType());
        System.out.println("ID:" + indexResponse.getId());
        System.out.println("版本:" + indexResponse.getVersion());
//        System.out.println("是否创建成功:" + indexResponse.isCreated());

        client.close();
    }

    /**
     * 使用es的帮助类来创建文档
     */
    @Test
    public void createDoc_3() throws Exception {
        XContentBuilder sourse = XContentFactory.jsonBuilder()
                .startObject()
                .field("id", "3")
                .field("title", "Elasticsearch是用Java开发的")
                .field("content", "并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎")
                .endObject();

        IndexResponse indexResponse = client.prepareIndex("blog01", "article", "3").setSource(sourse).get();

        // 获取响应信息
        System.out.println("索引:" + indexResponse.getIndex());
        System.out.println("类型:" + indexResponse.getType());
        System.out.println("ID:" + indexResponse.getId());
        System.out.println("版本:" + indexResponse.getVersion());
        System.out.println("是否创建成功:" + indexResponse.getShardInfo());

        client.close();
    }

    /**
     * 搜索文档数据,搜索单个索引
     */
    @Test
    public void testGetData_1() {
        GetResponse getResponse = client.prepareGet("blog01", "article", "2").get();
        System.out.println(getResponse.getSourceAsString());

        client.close();
    }

    /**
     * 搜索文档数据,搜索多个索引
     */
    @Test
    public void testGetData_2() {
        MultiGetResponse itemResponses = client.prepareMultiGet()
//                .add("blog01", "article", "1")
                .add("blog01", "article", "2", "3","1")
                .get();

        // 遍历获取的数据
        for (MultiGetItemResponse item : itemResponses) {
            GetResponse response = item.getResponse();
            System.out.println(response.getSourceAsString());
        }

        client.close();
    }

    /**
     * 更新文档数据
     */
    @Test
    public void testUpdate_1() throws Exception {
        UpdateRequest request = new UpdateRequest();
        request.index("blog01"); // 指定更新的index
        request.type("article"); // 指定更新的type
        request.id("1"); // 指定更新的id

        request.doc(XContentFactory.jsonBuilder()
                .startObject()
                .field("id", "1")
                .field("title", "更新:ElasticSearch是一个基于Lucene的搜索服务器")
                .field("content", "更新:它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口")
                .endObject());

        // 开始更新
        UpdateResponse updateResponse = client.update(request).get();

        // 获取响应信息
        System.out.println("索引:" + updateResponse.getIndex());
        System.out.println("类型:" + updateResponse.getType());
        System.out.println("ID:" + updateResponse.getId());
        System.out.println("版本:" + updateResponse.getVersion());
//        System.out.println("是否创建成功:" + updateResponse.isCreated());

        client.close();
    }

    /**
     * 更新文档数据
     */
    @Test
    public void testUpdate_2() throws Exception {
        // 开始更新
        UpdateResponse updateResponse = client.update(new UpdateRequest("blog01", "article", "2")
                .doc(XContentFactory.jsonBuilder().startObject()
                        .field("id", "2")
                        .field("title", "更新:我们建立一个网站或应用程序")
                        .field("content", "更新:但是想要完成搜索工作的创建是非常困难的")
                        .field("sea", "更新:sea sea sea sea") //可以添加字段
                        .endObject()
                )).get();


        // 获取响应信息
        System.out.println("索引:" + updateResponse.getIndex());
        System.out.println("类型:" + updateResponse.getType());
        System.out.println("ID:" + updateResponse.getId());
        System.out.println("版本:" + updateResponse.getVersion());
//        System.out.println("是否创建成功:" + updateResponse.isCreated());

        client.close();
    }

    /**
     * 更新文档数据,设置查询的条件,如果查询不到数据,就添加数据
     */
    @Test
    public void testUpdate_3() throws Exception {
        IndexRequest indexRequest = new IndexRequest("blog", "article", "4")
                .source(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("id", "4")
                        .field("title", "一个基于Lucene的搜索服务器")
                        .field("content", "它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口")
                        .endObject());

        // 设置更新的数据,如果查不到,则更新
        UpdateRequest updateRequest = new UpdateRequest("blog01", "article", "4")
                .doc(XContentFactory.jsonBuilder()
                        .startObject()
                        .field("title", "我们建立一个网站或应用程序,并要添加搜索功能")
                        .endObject())
                .upsert(indexRequest);

        UpdateResponse updateResponse = client.update(updateRequest).get();

        // 获取响应信息
        System.out.println("索引:" + updateResponse.getIndex());
        System.out.println("类型:" + updateResponse.getType());
        System.out.println("ID:" + updateResponse.getId());
        System.out.println("版本:" + updateResponse.getVersion());
//        System.out.println("是否创建成功:" + updateResponse.isCreated());

        client.close();
    }

    /**
     * 删除数据
     */
    @Test
    public void testDel() {
        DeleteResponse deleteResponse = client.prepareDelete("blog01", "article", "4").get();
//        System.out.println("是否返回结果:" + deleteResponse.isFound());
        System.out.println("是否返回结果:" + deleteResponse.getShardInfo());
        client.close();
    }

    /**
     * 查询文档数据
     */
    @Test
    public void testSearch() {
        // QueryString查询
        SearchResponse searchResponse = client.prepareSearch("blog01")
                .setTypes("article")
                .setQuery(QueryBuilders.queryStringQuery("引擎")) // 发现在查询是只是依据第一个字来查询
                .get();

        // 获取结果集对象,获取命中次数
        SearchHits hits = searchResponse.getHits();
        System.out.println("查询的结果数据有" + hits.getTotalHits() + "");
        // 遍历每条数据
        Iterator<SearchHit> it = hits.iterator();
        while (it.hasNext()) {
            SearchHit searchHit = it.next();
            // 打印整条信息
            System.out.println(searchHit.getSourceAsString());

            // 获取字段信息
//            System.out.println("id:" + searchHit.getSource().get("id"));
//            System.out.println("title:" + searchHit.getSource().get("title"));
//            System.out.println("content" + searchHit.getSource().get("content"));
            System.out.println("id:" + searchHit.getFields().get("id"));
            System.out.println("title:" + searchHit.getFields().get("title"));
            System.out.println("content" + searchHit.getFields().get("content"));
        }


        client.close();
    }

    /**
     * 创建索引
     */
    @Test
    public void testCreateIndex() {
        // 创建index
        client.admin().indices().prepareCreate("blog01").get();

        // 删除index
//        client.admin().indices().prepareDelete("blog01").get();
    }

    /**
     * 创建一个带有映射的索引 ,先创建索引
     */
    @Test
    public void testCreateIndexAndMapping() throws Exception {
        final XContentBuilder mappingBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .startObject("article")
                .startObject("properties")
                .startObject("id")
                .field("type", "integer").field("store", "yes")
                .endObject()
                .startObject("title")
                .field("type", "string").field("store", "yes").field("analyzer", "ik_max_word")
                .endObject()
                .startObject("content")
                .field("type", "string").field("store", "yes").field("analyzer", "ik_max_word")
                .endObject()
                .endObject()
                .endObject()
                .endObject();

        PutMappingRequest request = Requests.putMappingRequest("blog01")
                .type("article")
                .source(mappingBuilder);

        client.admin().indices().putMapping(request).get();

        client.close();
    }


    /**
     * 各种查询
     */
    @Test
    public void testSearchMapping() {
        // queryString查询
//        SearchResponse searchResponse = client.prepareSearch("blog01")
//                .setTypes("article")
//                .setQuery(QueryBuilders.queryStringQuery("引擎"))
//                .get();

        // 词条查询
        // 它仅匹配在给定的字段中去查询,而且是查询含有该词条的内容
//        SearchResponse searchResponse = client.prepareSearch("blog01")
//                .setTypes("article")
//                .setQuery(QueryBuilders.termQuery("content", "引擎"))
//                .get();

        // 通配符查询
//        SearchResponse searchResponse = client.prepareSearch("blog01")
//                .setTypes("article")
//                .setQuery(QueryBuilders.wildcardQuery("content", "接?"))
//                .get();

        // 模糊查询
//        SearchResponse searchResponse = client.prepareSearch("blog01")
//                .setTypes("article")
//                .setQuery(QueryBuilders.fuzzyQuery("title", "Lucena"))
//                .get();

        // 解析字符串查询,指定字段
//        SearchResponse searchResponse = client.prepareSearch("blog01")
//                .setTypes("article")
//                .setQuery(QueryBuilders.queryStringQuery("接口").field("content").field("title"))
//                .get();

        // 字段匹配查询
//        SearchResponse searchResponse = client.prepareSearch("blog01").setTypes("article")
//                .setQuery(QueryBuilders.matchPhrasePrefixQuery("title", "服 ").slop(1))
//                .get();

        // 范围查询
        SearchResponse searchResponse = client.prepareSearch("blog01").setTypes("article")
                .setQuery(QueryBuilders.rangeQuery("id")
                        //.from("它提供").to("引擎").includeLower(true).includeUpper(true))
                        .gt(1).lt(4))
                .get();


        this.getHits(searchResponse);

        client.close();
    }


    /**
     * 查看响应信息方法
     */
    public void getHits(SearchResponse searchResponse) {
        // 获取结果集对象,获取命中次数
        SearchHits hits = searchResponse.getHits();
        System.out.println("查询的结果数据有" + hits.getTotalHits() + "");
        // 遍历每条数据
        Iterator<SearchHit> it = hits.iterator();
        while (it.hasNext()) {
            SearchHit searchHit = it.next();
            // 打印整条信息
            System.out.println(searchHit.getSourceAsString());

            // 获取字段信息
            System.out.println("id:" + searchHit.getFields().get("id"));
            System.out.println("title:" + searchHit.getFields().get("title"));
            System.out.println("content" + searchHit.getFields().get("content"));
        }
    }



}

 

方式2:

  <dependencies>
      <dependency>
          <groupId>org.elasticsearch</groupId>
          <artifactId>elasticsearch</artifactId>
          <version>6.5.3</version>
      </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.12</version>
      </dependency>
  </dependencies>

 

private Client client;
    /** 获取client */
    @Before
    public void getClient() throws Exception {
        client = TransportClient.builder().build()
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
    }

 

条件查询QueryBuilder

到目前为止,我们使用了REST API和简单查询以及GET请求来搜索数据。更改索引时,无论想执行的操作是更改映射还是文档索引化,都要用REST API向Elasticsearch发送JSON结构的数据。类似地,如果想发送的不是一个简单的查询,仍然把它封装为JSON结构并发送给Elasticsearch。这就是所谓的查询DSL。从更宏观的角度看,Elasticsearch支持两种类型的查询:基本查询和复合查询。

基本查询,如词条查询用于查询实际数据。

第二种查询为复合查询,如布尔查询,可以合并多个查询。

查询数据 主要依赖QueryBuilder对象 ,可以通过QueryBuilders获取各种查询 :(基于lucene)

boolQuery() 布尔查询,可以用来组合多个查询条件 
fuzzyQuery() 模糊查询
matchAllQuery() 查询所有数据
regexpQuery() 正则表达式查询
termQuery() 词条查询
wildcardQuery() 通配符查询

使用SearchResponse获取,支持各种查询:

 /**
     * 搜索在elasticSearch中创建的文档对象
     */
    @Test
    public void testSearch() throws Exception {
        // 搜索数据
        // get()方法 === execute().actionGet()
        // SearchResponse searchResponse = client.prepareSearch("blob1")
        // .setTypes("article").setQuery(QueryBuilders.matchAllQuery()).get();
        /**
         * 1、ElasticSearch提供QueryBuileders.queryStringQuery(搜索内容)
         * 查询方法,对所有字段进行分词查询
         */
//        SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
//                .setQuery(QueryBuilders.queryStringQuery("全面"))
//                .get();
        /**
         * 2、 只想查询content里包含全文 ,使用QueryBuilders.wildcardQuery模糊查询 *任意字符串 ?任意单个字符
         */
//        SearchResponse searchResponse = client.prepareSearch("blog").setTypes("article")
//                .setQuery(QueryBuilders.wildcardQuery("content", "*全文*")).get();
        /** 3、 查询content词条为“搜索” 内容,使用TermQuery */
        SearchResponse searchResponse = client.prepareSearch("blog")
                .setTypes("article")
                .setQuery(QueryBuilders.termQuery("content", "全文")).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象
        System.out.println("查询结果有:" + hits.getTotalHits() + "");
        Iterator<SearchHit> iterator = hits.iterator();
        while (iterator.hasNext()) {
            SearchHit searchHit = iterator.next(); // 每个查询对象
            System.out.println(searchHit.getSourceAsString()); // 获取字符串格式打印
            System.out.println("id:" + searchHit.getSource().get("id"));
            System.out.println("title:" + searchHit.getSource().get("title"));
            System.out.println("content:" + searchHit.getSource().get("content"));
            for (Iterator<SearchHitField> ite = searchHit.iterator(); ite.hasNext();) {
                SearchHitField next = ite.next();
                System.out.println(next.getValues());
            }
        }
        // 关闭连接
        client.close();
    }

 

各种查询对象Query的使用:

ElasticSearch 支持所有Lucene查询,并对其进行简化封装

WildcardQuery 通配符查询
TermQuery 词条查询 
FuzzyQuery 相似度查询(模糊查询)
BooleanQuery 布尔查询 

 

1、ElasticSearch提供QueryBuileders.queryStringQuery(搜索内容) 查询方法,对所有字段进行分词查询 
SearchResponse searchResponse = client.prepareSearch("blog")
         .setTypes("article")
         .setQuery(QueryBuilders.queryStringQuery("全文")).get();
2、 只想查询content里包含全文 ,使用QueryBuilders.wildcardQuery通配符查询 *任意字符串 ?任意单个字符 
    SearchResponse searchResponse = client.prepareSearch("blog")
         .setTypes("article")
         .setQuery(QueryBuilders.wildcardQuery("content", "*全文*")).get();
    发现查询不到!!!! ,涉及词条查询理解, 说明没有词条包含“全文”
3、 查询content词条为“搜索” 内容,使用QueryBuilders.termQuery进行词条查询 
        SearchResponse searchResponse = client.prepareSearch("blog")
        .setTypes("article")
        .setQuery(QueryBuilders.termQuery("content", "全文")).get();
    发现查询不到!!!,说明没有搜索“全文”这个词条 
这是为什么呢?
词条: 就是将文本内容存入搜索服务器,搜索服务器进行分词之后的内容。
例如:“ElasticSearch是一个基于Lucene的搜索服务器”
    分词(好的): ElasticSearch、是、一个、基于、Lucene、搜索、服务、服务器 
    默认单字分词(差的): ElasticSearch、 是、一、个、基、于、搜、索
    使用QueryBuileders.queryStringQuery(搜索内容),搜索“全面” 也能够查询到,这是为什么呢?看图:

 

 

 

3.30.20 queryStringQuery搜索内容查询

解析查询字符串 相比其他可用的查询,query_string查询支持全部的Apache Lucene查询语法 针对多字段的query_string查询

SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
                 .setQuery(QueryBuilders.queryStringQuery("全面")).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

3.30.21 wildcardQuery通配符查询

*匹配多个字符,?匹配1个字符

注意:避免* 开始, 会检索大量内容造成效率缓慢

SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
                 .setQuery(QueryBuilders.wildcardQuery("content", "elas*c?")).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

3.30.22 termQuery词条查询

词条查询是Elasticsearch中的一个简单查询。它仅匹配在给定字段中含有该词条的文档,而

且是确切的、未经分析的词条

termQuery("key", obj) 完全匹配

termsQuery("key", obj1, obj2..) 一次匹配多个值,只要有一个值是正确的,就可以查询出数据

//        SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
//                 .setQuery(QueryBuilders.termQuery("content", "搜索")).get();
        SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
                 .setQuery(QueryBuilders.termsQuery("content", "搜索","全文")).get();
SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

字段匹配查询

matchQuery("key", Obj) 单个匹配, field不支持通配符, 前缀具高级特性 match查询把query参数中的值拿出来,加以分析,然后构建相应的查询。

使用match查询时,Elasticsearch将对一个字段选择合适的分析器,所以可以确定,传给match查询的词条将被建立索引时相同的分析器处理。

multiMatchQuery("text", "field1", "field2"..); 匹配多个字段, field有通配符查询功能

//        SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
//                 .setQuery(QueryBuilders.matchQuery("content", "搜索")).get();
        SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
                .setQuery(QueryBuilders.multiMatchQuery("搜索", "title","content")).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

只查询ID(标识符查询) 标识符查询是一个简单的查询,仅用提供的标识符来过滤返回的文档。此查询针对内部的 uid字段运行,所以它不需要启用id字段

SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
                .setQuery(QueryBuilders.idsQuery().ids("1")).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

3.30.23 boolQuery布尔查询

用于复杂搜索逻辑的BoolQuery

 public SearchResponse getSimpleSearchResponse( int page, int pagesize){
 
         BoolQueryBuilder mustQuery = QueryBuilders.boolQuery();
         mustQuery.must(QueryBuilders.matchAllQuery()); // 添加第1条must的条件 此处为匹配所有文档
 
         mustQuery.must(QueryBuilders.matchPhraseQuery("title", "时间简史"));//添加第2条must的条件 title字段必须为【时间简史】
         // ↑ 放入筛选条件(termQuery为精确搜索,大小写敏感且不支持*) 实验发现matchPhraseQuery可对中文精确匹配term
 
         mustQuery.must(QueryBuilders.matchQuery("auther", "霍金")); // 添加第3条must的条件
 
         QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("物理")//.escape(true)//escape 转义 设为true,避免搜索[]、结尾为!的关键词时异常 但无法搜索*
                 .defaultOperator(QueryStringQueryBuilder.Operator.AND);//不同关键词之间使用and关系
         mustQuery.must(queryBuilder);//添加第4条must的条件 关键词全文搜索筛选条件
 
         SearchRequestBuilder searchRequestBuilder = EsClient.getClient().prepareSearch("index name").setTypes("type name")
                 .setQuery(mustQuery)
                 .addHighlightedField("*")/*星号表示在所有字段都高亮*/.setHighlighterRequireFieldMatch(false)//配置高亮显示搜索结果
                 .setHighlighterPreTags("<高亮前缀标签>").setHighlighterPostTags("<高亮后缀标签>");//配置高亮显示搜索结果
 
                 searchRequestBuilder = searchRequestBuilder.addAggregation(AggregationBuilders.terms("agg1(聚类返回时根据此key获取聚类结果)")
                         .size(1000)/*返回1000条聚类结果*/.field("要在文档中聚类的字段,如果是嵌套的则用点连接父子字段,如【person.company.name】"));
 
         SearchResponse searchResponse = searchRequestBuilder.setFrom((page - 1) * pagesize)//分页起始位置(跳过开始的n个)
                 .setSize(pagesize)//本次返回的文档数量
                 .execute().actionGet();//执行搜索
 
         log.info("response="+searchResponse);
         return searchResponse;
     }
 }

3.30.24 fuzzyQuery模糊查询

相似度查询 fuzzy查询是模糊查询中的第三种类型,它基于编辑距离算法来匹配文档

SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
                .setQuery(QueryBuilders.fuzzyQuery("content", "elasticsearxx")).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

范围查询 范围查询使我们能够找到在某一字段值在某个范围里的文档,字段可以是数值型,也可以是 基于字符串的

SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
                .setQuery(QueryBuilders.rangeQuery("content").from("我们").to("解决方案").includeLower(true).includeUpper(true)).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

includeLower(true):包含上界
IncludeUpper(true):包含下界

**跨度查询**
下面代码表示,从首字母开始,查询content字段=问题的数据,问题前面的词为300个,可以测试30看是否能查询出数据。

SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
                .setQuery(QueryBuilders.spanFirstQuery(QueryBuilders.spanTermQuery("content", "问题"), 300)).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

组合查询(复杂查询)

     must(QueryBuilders) : AND
     mustNot(QueryBuilders): NOT
     should(QueryBuilders):OR 
在定义json:放置到Elasticsearch的插件中
{
    "query": {
        "bool": {
            "must": {
                "term": {
                    "title": "elasticsearch"
                }
            },
            "should": {
                "range": {
                    "id": {
                        "from": 1,
                        "to": 2
                    }
                }
            }
        }
    }
}
SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
                .setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("title", "搜索")).must(QueryBuilders.wildcardQuery("content", "elastic*ch"))).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

排序查询

SearchResponse searchResponse = client.prepareSearch("blog2").setTypes("article")
                .setQuery(QueryBuilders.matchAllQuery())
                .addSort("id", SortOrder.DESC).get();
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

3.30.25 regexpQuery正则表达式查询

正则表达式查询

responsebuilder.setQuery(QueryBuilders.regexpQuery(field, regexp))

/**
     * 高亮显示查询
     * 获取数据,
     *  查询apache,不仅在author拥有,也可以在url,在name中也可能拥有
     *  author or url   --->booleanQuery中的should操作
     *      如果是and的类型--->booleanQuery中的must操作
     *      如果是not的类型--->booleanQuery中的mustNot操作
     *  使用的match操作,其实就是使用要查询的keyword和对应字段进行完整匹配,是否相等,相等返回
     */
@Test
public void testSearch4() {
    SearchResponse response = client.prepareSearch(indics).setSearchType(SearchType.DEFAULT)
        //                .setQuery(QueryBuilders.multiMatchQuery("apache", "author", "url"))
        //                .setQuery(QueryBuilders.regexpQuery("url", ".*apache.*"))
        //                .setQuery(QueryBuilders.termQuery("author", "apache"))
        .setQuery(QueryBuilders.boolQuery()
                  .should(QueryBuilders.regexpQuery("url", ".*apache.*"))
                  .should(QueryBuilders.termQuery("author", "apache")))
        // 设置高亮显示--->设置相应的前置标签和后置标签
        .setHighlighterPreTags("<span color='blue' size='18px'>")
        .setHighlighterPostTags("</span>")
        // 哪个字段要求高亮显示
        .addHighlightedField("author")
        .addHighlightedField("url")
        .get();
    SearchHits searchHits = response.getHits();
    float maxScore = searchHits.getMaxScore();  // 查询结果中的最大文档得分
    System.out.println("maxScore: " + maxScore);
    long totalHits = searchHits.getTotalHits(); // 查询结果记录条数
    System.out.println("totalHits: " + totalHits);
    SearchHit[] hits = searchHits.getHits();    // 查询结果
    System.out.println("当前返回结果记录条数:" + hits.length);
    for(SearchHit hit : hits) {
        System.out.println("========================================================");
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        for(Map.Entry<String , HighlightField> me : highlightFields.entrySet()) {
            System.out.println("--------------------------------------");
            String key = me.getKey();
            HighlightField highlightField = me.getValue();
            String name = highlightField.getName();
            System.out.println("key: " + key + ", name: " + name);
            Text[] texts = highlightField.fragments();
            String value = "";
            for(Text text : texts) {
                // System.out.println("text: " + text.toString());
                value += text.toString();
            }
            System.out.println("value: " + value);
        }
    }
}

 

3.30.26 matchAllQuery查询所有数据

查询所有

matchAllQuery()匹配所有文件

match_all查询是Elasticsearch中最简单的查询之一。它使我们能够匹配索引中的所有文件。

SearchResponse searchResponse = client.prepareSearch("blog2")
             .setTypes("article").setQuery(QueryBuilders.matchAllQuery())
             .get();
        
        SearchHits hits = searchResponse.getHits(); // 获取命中次数,查询结果有多少对象

 

 

posted on 2020-12-14 14:10  lshan  阅读(210)  评论(0编辑  收藏  举报