基于文档的基本操作

Rest风格是一种软件架构风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

methodurl地址描述
PUTlocalhost:9200/索引名称/类型名称/文档id创建文档(指定文档id)
POSTlocalhost:9200/索引名称/类型名称创建文档(随机文档id)
POSTlocalhost:9200/索引名称/类型名称/文档id/_update修改文档
POSTlocalhost:9200/索引名称/类型名称/_search查询所有数据
DELETElocalhost:9200/索引名称/类型名称/文档id删除文档
GETlocalhost:9200/索引名称/类型名称/文档id查询文档通过文档id

1、创建三条记录:

POST /kexing/user/1
{
  "name": "kexing",
  "age":12,
  "motto":"只要学不死,就往死里学"
}

POST /kexing/user/2
{
  "name": "张三与kexing",
  "age":20,
  "motto":"No more"
}

POST /kexing/user/3
{
  "name": "李四",
  "age":25,
  "motto":"No more"
}

2、获取记录GET

GET kexing/user/1

3、修改数据POST(如果使用GET或着不用_update则会直接覆盖原来的document)

POST /kexing/user/1/_update
{
  "doc":{
    "age":13
  }
}

version为记录更改的次数

#! Deprecation: [types removal] Specifying types in document update requests is deprecated, use the endpoint /{index}/_update/{id} instead.
{
  "_index" : "kexing",
  "_type" : "user",
  "_id" : "1",
  "_version" : 2,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 3,
  "_primary_term" : 1
}

4、条件查询

GET /kexing/_search?q=name:张三

IK分词器会先把词进行一次分词,然后再进行精确的查询,"张三与kexing"被拆分成了"张三","与", "kexing"。

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.5180674,
    "hits" : [
      {
        "_index" : "kexing",
        "_type" : "user",
        "_id" : "2",
        "_score" : 1.5180674,
        "_source" : {
          "name" : "张三与kexing",
          "age" : 20,
          "motto" : "No more"
        }
      }
    ]
  }
}

5、复杂查询

_source查询对应的字段,结果过滤,相当于select name,age from xxx

sort根据字段排序,desc降序,asc升序

from size分页(startpagesize

GET /kexing/user/_search
{
  "query": {
    "match": {
      "name": "kexing"
    }
  }
  , "_source": ["name","age"]
  , "sort": [
    {
      "age": {
        "order": "desc"
      }
    }
  ]
  
, "from": 0
  , "size": 1
}

6、布尔查询

must(and)匹配,where name=xxx and age=xxx

GET /kexing/user/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "kexing"
          }
        },
        {
          "match": {
            "age": 14
          }
        }
      ]
    }
  }
}

should(or)匹配,where name=xxx or age=xxx

GET /kexing/user/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "name": "kexing"
          }
        },
        {
          "match": {
            "age": 14
          }
        }
      ]
    }
  }
}

关于分词:

  • term是代表完全匹配,也就是精确查询,搜索前不会对搜索词进行分词,也就是匹配已有记录中被分词器拆分的词。
  • match查询会先对搜索词进行分词,分词完毕后再逐个对分词结果进行匹配,因此相比于term的精确搜索,match是分词匹配搜索,match搜索还有两个相似功能的变种,一个是match_phrase,一个是multi_match

7、搜索高亮:

highlight可将需要高亮显示的字段高亮

pre_tagspost_tags属性可以自定义高亮样式,分别为前缀和后缀

GET kexing/user/_search
{
  "query": {
    "match": {
      "name": "kexing"
    }
  }
  
  , "highlight": {
    "pre_tags": "<span style='color:red'>", 
    "post_tags": "</span>", 
    "fields": {
      "name":{}
    }
  }
}
#! Deprecation: [types removal] Specifying types in search requests is deprecated.
{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 0.6133945,
    "hits" : [
      {
        "_index" : "kexing",
        "_type" : "user",
        "_id" : "1",
        "_score" : 0.6133945,
        "_source" : {
          "name" : "kexing",
          "age" : 14,
          "motto" : "只要学不死,就往死里学"
        },
        "highlight" : {
          "name" : [
            "<span style='color:red'>kexing</span>"
          ]
        }
      },
      {
        "_index" : "kexing",
        "_type" : "user",
        "_id" : "2",
        "_score" : 0.36372143,
        "_source" : {
          "name" : "张三与kexing",
          "age" : 20,
          "motto" : "No more"
        },
        "highlight" : {
          "name" : [
            "张三与<span style='color:red'>kexing</span>"
          ]
        }
      }
    ]
  }
}

整合SpringBoot

1、导入pom

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

2、配置高级客户端到Spring容器中

@Configuration
public class EsConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost", 9200, "http")));
        return client;
    }
}

3、简单API使用

@RunWith(SpringRunner.class)
@SpringBootTest
public class EsAPI {
    public static final String INDEX = "kexing_index";

    //注入es高级客户端
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;

    //******************************索引API**************************************

    /**
     * 创建索引
     * @throws IOException
     */
    @Test
    public void createIndex() throws IOException {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(INDEX);
        client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
    }

    /**
     * 删除索引
     * @throws IOException
     */
    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(INDEX);
        client.indices().delete(deleteIndexRequest,RequestOptions.DEFAULT);
    }

    //******************************文档API**************************************

    /**
     * 创建文档
     * @throws IOException
     */
    @Test
    public void createDocument() throws IOException {
        //根据哪个索引创建
        IndexRequest indexRequest = new IndexRequest(INDEX);
        indexRequest.id("1");
        //填充文档内容
        indexRequest.source(JSON.toJSONString(new User("kexing",12,"2020/4/30")), XContentType.JSON);
        //执行请求,返回响应
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(indexResponse.status());
    }

    /**
     * 删除文档
     * @throws IOException
     */
    @Test
    public void deleteDocument() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(INDEX,"1");
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(deleteResponse.status());
    }

    /**
     * 修改文档
     * @throws IOException
     */
    @Test
    public void updateDocument() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(INDEX,"1");
        updateRequest.doc(JSON.toJSONString(new User("kexing",20,"2000/7/3")),XContentType.JSON);
        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(updateResponse.status());
    }

    /**
     * 获取文档信息
     * @throws IOException
     */
    @Test
    public void getDocument() throws IOException {
        GetRequest getRequest = new GetRequest(INDEX, "1");
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        String res = getResponse.getSourceAsString();
        System.out.println(res);
    }

    /**
     * term查询
     * @throws IOException
     */
    @Test
    public void searchDocument() throws IOException {
        SearchRequest searchRequest = new SearchRequest(INDEX);
        //构建查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.termQuery("name","kexing"));
        searchSourceBuilder.timeout(TimeValue.timeValueSeconds(2));
        //查询
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        String res = JSON.toJSONString(searchResponse.getHits());
        System.out.println(res);
    }

    /**
     * bulk批量插入
     * @throws IOException
     */
    @Test
    public void Insert() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (int i = 0; i < 20; i++) {
            bulkRequest.add(
                    new IndexRequest(INDEX)
                            .id(i+1+"")
                            .source(JSON.toJSONString(new User("kexing"+i+1,i+1,"2000/7/3")),XContentType.JSON));
        }
        BulkResponse bulkResponse = client.bulk(bulkRequest,RequestOptions.DEFAULT);
        System.out.println(bulkResponse.hasFailures());
    }
}
最后修改:2021 年 04 月 25 日 05 : 07 PM
如果觉得我的文章对你有用,请随意赞赏