1.通过elasticsearch-head 创建

(1)登录localhost:9100

(2)点击复合查询

(3)输入内容

(4)勾选易读,点击验证是否是JSON格式

(5)点击提交请求,返回

{

  • "acknowledged": true

}

2.通过postman来创建索引:

(1)选择请求格式PUT,输入请求访问地址:127.0.0.1:9200/peoper

(2)选择下面的Body->raw->JSON(application/json)

(3)创建索引,例如:

{
 "settings":{
  "number_of_shards":3, //创建分片数
  "number_of_replicas":1//创建备份数
 },
 "mappings":{
  "man":{
   "properties":{
    "name":{
     "type":"text"
    },
    "country":{
     "type":"keyword"
    },
    "age":{
     "type":"integer"
    },
    "data":{
     "type":"date",
     "format":"yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
    
    }
   }
  }
 }
}

(4)点击send ,如果格式正确会返回如下信息:

{
    "acknowledged": true,
    "shards_acknowledged": true,
    "index": "peoper"
}

(5)现在索引就创建好了,返回elasticsearch-head 的页面刷新就能看到

3.在postman中对索引进行插入数据

(1)选择访问请求为POST ,请求内容:127.0.0.1:9200/peoper/man/(也可以在后面跟上ID号,不跟是自动自增长ID)

(2)根据创建索引是创建的数据格式,插入数据如下:

{
 "name":"王尼玛",
 "country":"China",
 "age":35,
 "date":"1987-12-08"
}

如国数据添加成功会返回信息如下:

(3)在浏览器中点击刷新,就能够看到数据增加一条。点击数据浏览找到对应的索引就能看到插入数据的内容。

4.使用postman直接修改文档(指定修改文件的内容)

(1)请求访问类型为POST,请求访问内容输入:127.0.0.1:9200/peoper/man/1/_update(修改索引peoper下man对象ID为1的数据,后面的_update修改必须更上)

(2)修改内容如下:

{

"doc":{

"name":"baing"

}

}

其中修改的数据必须放在:“doc”:{}中

5.使用脚本修改文档(使用postman)

(1)请求访问类型为POST,请求访问内容输入:127.0.0.1:9200/peoper/man/1/_update(修改索引peoper下man对象ID为1的数据,后面的_update修改必须更上)

(2)修改内容如下:

{

"script":{   //使用脚本语言的类型

"lang":"painless",  //lang为语言,painless为内置的语言还可以是python

"inline":"ctx._source.age += 15"  //获取当前年龄在加上15

}

}

5.删除对应的数据

6.查询

(1)简单查询:

在postman中选择GET  内容为127.0.0.1:9200/peoper/man/1

(2)条件查询

类型选择POST 内容为:127.0.0.1:9200/peoper/_search

查询条件:

{
"query":{
 "match_all":{}
}
}

这样就查出所有的内容

图中“from”表示从第几条数据开始,“size”表示返回一条数据

表示查询出标题中含有“elasticsearch”的内容通过“publish_date”这个字段进行降序

(3)聚合查询

图中"aggs"为聚合查询的关键自,"group_by_word_count"自定义根据字数查询的名字,“word_count”表示根据这个字段去查询统计

. 条件查询
{
"query":{
"match":{
"title":"elasticsearch"
}
},
"from": 1,
"size": 2,
"sort":[{"publish_date":"desc"}]
}

match_all :表示查询所有 match : 表示条件查询 from : 表示返回结果从第几页开始 size : 表示返回结果的大小 sort : 表示排序

6. 聚合查询
{
"aggs": {
"group_by_word_count": {
"terms":{
"field":"word_count"
}
},
"group_by_publish_date":{
"terms":{
"field":"publish_date"
}
}
}
}

aggs: 表明是聚合查询 "group_by_word_count":自定义名称,可以随意 terms:关键字 field:使用的字段

7. 统计查询
{
"aggs": {
"grand_word_count":{
"stats":{
"field":"word_count"
}
}
}
}

返回结果:

aggregations":{
"grand_word_count":{
"count": 8,
"min": 2000,
"max": 5000,
"avg": 3375,
"sum": 27000
}
}

说明: aggs:统计查询 grand_word_count:自定义名称 stats:统计方法,可以换成min/max/sum field:进行统计的字段

8. 高级查询

高级查询分为子条件查询和复合查询

1. 子条件查询:特定字段查询所指特定值
1. query context

在查询过程中,除了判断文档是否满足查询条件外,ES还会计算一个_score来标识匹配的程度,旨在判断目标文档和查询条件匹配的有多好.

常用查询:

  1. 全文本查询: 针对文本类型的查询

a. 模糊匹配:

​ post - http://127.0.0.1:9200/book/_search

{
"query":{
"match":{
"title":"ElastichSearch入门"
}
}
}

​ 从结果中可以看出,结果会匹配ElasticSearch入门,他们的关系是或的关系,相当于自动分词

b. 习语匹配

{
"query":{
"match_phrase":{
"title": "ElasticSearch入门"
}
}
}

从结果中可以看出,会把ElasticSearch入门当做一个整体的词进行匹配

c. 多个字段的模糊查询

{
"query":{
"multi_match":{
"query":"瓦力",
"fields":["author","title"]
}
}
}

d. querystring,语法查询()

{
"query":{
"query_string":{
"query":"(ElasticSearch) AND 入门) OR Python"
}
}
}
{
"query":{
"query_string":{
"query":"瓦力 OR ElasticSearch",
"fields":["author","title"]
}
}
}

2). 字段级别的查询: 针对结构化数据,如数字,日期等

{
"query":{
"term":{
"word_count":1000
}
}
}

term : 表示具体的字段查询

还可以指定范围:

{
"query":{
"range":{
"word_count":{
"gte": 1000,
"lte": 2000
}
}
}
}

关键词:range表明是范围查询,后面跟具体的字段,gte表示>=,lte表示<=

范围,还可以用在日期上.

2. filter context

在查询过程中,只判断该文档是否满足条件,只有Yes或No

{
"query":{
"bool":{
"filter":{
"term":{
"word_count":1000
}
}
}
}
}

filter结合bool使用

2. 复合条件查询:以一定的逻辑组合子条件查询
1. 固定分数查询
{
"query":{
"constant_score":{
"filter":{
"match":{
"title":"ElasticSearch"
}
},
"boost":2
}
}
}

constant_score:固定分数,即把_score的值指定,如果不加boost则为1,指定了boost的值,则_score等于boost的值

注意: constant_score不支持match

2. bool查询
{
"query":{
"bool":{
"should":[
{
"match":{
"author":"瓦力"
}
},
{
"match":{
"title":"ElasticSearch"
}
}
]
}
}
}

should为关键词,应该满足他列出的条件,是或的关系

{
"query":{
"bool":{
"must":[
{
"match":{
"author":"瓦力"
}
},
{
"match":{
"title":"ElasticSearch"
}
}
]
}
}
}

must:与的关系

must和filter

{
"query":{
"bool":{
"must":[
{
"match":{
"author":"瓦力"
}
},
{
"match":{
"title":"ElasticSearch"
}
}
],
"filter:[
"term":{
"word_count":1000
}
]
}
}
}

即在满足must中的条件的同时,还有满足过滤条件的数据才会最终返回.

must的反义词mustnot

{
"query":{
"mustnot":{
"term":{
"author":"wali"
}
}
}
}

一定不能满足该条件.

9. springboot集成ES

  1. 引入指定的版本

    		<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.5.2</version>
    </dependency> <dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.5.2</version>
    </dependency> <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.7</version>
    </dependency>

    transport 5.5.2 默认的不是ElasticSearch 5.5.2,要使用指定的版本必须声明ElasticSearch的版本,如果依然冲突,在transport中使用exclusions

  2. 配置

@Configuration
public class MyConfig {
@Bean
public TransportClient client() throws UnknownHostException {
InetSocketTransportAddress node = new InetSocketTransportAddress(
InetAddress.getByName("localhost"),
9300 //tcp
); Settings settings = Settings.builder()
.put("cluster.name","wali")
.build();
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(node);//可以增加多个节点
return client;
}
}
3. 相关操作
  @Autowired
private TransportClient client; @GetMapping("/get/book/novel")
@ResponseBody
public ResponseEntity get(@RequestParam(value = "id", defaultValue = "") String id) {
if (id.isEmpty())
return new ResponseEntity(HttpStatus.NOT_FOUND);
GetResponse result = client.prepareGet("book", "novel", id).get();
if (!result.isExists()) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
return new ResponseEntity(result, HttpStatus.OK);
} @PutMapping("/put/book/novel")
@ResponseBody
public ResponseEntity add(
@RequestParam("title") String title,
@RequestParam("author") String author,
@RequestParam("word_count") int wordCount,
@RequestParam("publish_date")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date publishDate
) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(publishDate));
try {
XContentBuilder contentBuilder =
XContentFactory.jsonBuilder().startObject()
.field("title", title)
.field("author", author)
.field("word_count", wordCount)
.field("publish_date", format.format(publishDate))
.endObject();
System.out.println(contentBuilder.toString());
IndexResponse result =
client.prepareIndex("book", "novel")
.setSource(contentBuilder).get(); return new ResponseEntity(result.getId(), HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
} @DeleteMapping("/delete/book/novel")
@ResponseBody
public ResponseEntity delete(@RequestParam("id") String id) { DeleteResponse result =
this.client.prepareDelete("book", "novel", id).get();
return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
} @PutMapping("/update/book/novel")
@ResponseBody
public ResponseEntity update(
@RequestParam(value = "id", required = true) String id,
@RequestParam(value = "title", required = false) String title,
@RequestParam(value = "author", required = false) String author,
@RequestParam(value = "word_count", required = false)
Integer wordCount,
@RequestParam(value = "publish_date", required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
Date publishDate
) {
UpdateRequest updateRequest = new UpdateRequest("book", "novel", id);
try {
XContentBuilder contentBuilder =
XContentFactory.jsonBuilder().startObject();
if (title != null)
contentBuilder.field("title", title);
if (author != null)
contentBuilder.field("author", author);
if (wordCount != null)
contentBuilder.field("word_count", wordCount);
if (publishDate != null)
contentBuilder.field("publish_date",
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(publishDate));
contentBuilder.endObject();
updateRequest.doc(contentBuilder);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
} try {
UpdateResponse result = this.client.update(updateRequest).get();
return new ResponseEntity(result.getResult().toString(), HttpStatus.OK);
} catch (InterruptedException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (ExecutionException e) {
e.printStackTrace();
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
} }//update @PostMapping("/query/book/novel")
@ResponseBody
public ResponseEntity query(
@RequestParam(value = "title", required = false) String title,
@RequestParam(value = "author", required = false) String author,
@RequestParam(value = "lt_word_count", required = false) Integer ltWordCount,
@RequestParam(value = "gt_word_count", required = false, defaultValue = "0")
Integer gtWordCount
) {
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
if (title != null)
boolQuery.must(QueryBuilders.matchQuery("title", title));
if (author != null)
boolQuery.must(QueryBuilders.matchQuery("author", author)); RangeQueryBuilder rangeQuery =
QueryBuilders.rangeQuery("word_count")
.from(gtWordCount);
if (ltWordCount != null)
rangeQuery.to(ltWordCount);
boolQuery.filter(rangeQuery); SearchRequestBuilder searchRequestBuilder =
this.client.prepareSearch("book")
.setTypes("novel")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(boolQuery)
.setFrom(0)
.setSize(10);
System.out.println(searchRequestBuilder);
SearchResponse searchResponse = searchRequestBuilder.get(); List<Map<String, Object>> result = new ArrayList<>(); for (SearchHit searchHit : searchResponse.getHits()) {
result.add(searchHit.getSource());
}
return new ResponseEntity(result, HttpStatus.OK);
}

elasticsearch创建索引的更多相关文章

  1. Elasticsearch创建索引和映射结构详解

    前言 这篇文章详细介绍了如何创建索引和某个类型的映射. 下文中[address]指代elasticsearch服务器访问地址(http://localhost:9200). 1       创建索引 ...

  2. elasticsearch 创建索引,以及检索一条数据

    elasticsearch的重要概念 我们可以把elasticsearch当做数据库来理解: index:索引库名称,相当于关系型数据库中的表名,一个elasticsearch集群中可以有多个索引库. ...

  3. elasticsearch 创建索引

    一.基本概念 索引:含有相同属性的文档的集合. //可以想象成一个数据库 database 类型:索引可以定义一个或多个类型,文档必须属于一个类型. //可以想象成数据库中的表 table 文档:文档 ...

  4. Elasticsearch 使用集群 - 创建索引

    章节 Elasticsearch 基本概念 Elasticsearch 安装 Elasticsearch 使用集群 Elasticsearch 健康检查 Elasticsearch 列出索引 Elas ...

  5. [搜索]ElasticSearch Java Api(一) -添加数据创建索引

    转载:http://blog.csdn.net/napoay/article/details/51707023 ElasticSearch JAVA API官网文档:https://www.elast ...

  6. Elasticsearch 创建以及修改索引结构

    从问题出发,这篇内容可以解决以下几个问题: 一:如何开启关闭Es索引(数据库)? 二:如何创建索引(数据库)结构? 三:如何向已有索引(数据库)中添加类型(表)结构? 四:如何向已有类型(表)中添加新 ...

  7. elasticsearch自动按天创建索引脚本

    elasticsearch保存在一个索引中数据量太大无法查询,现在需要将索引按照天来建,查询的时候关联查询即可 有时候es集群创建了很多索引,删不掉,如果是测试环境或者初始化es集群(清空所有数据), ...

  8. ElasticSearch(六):IK分词器的安装与使用IK分词器创建索引

    之前我们创建索引,查询数据,都是使用的默认的分词器,分词效果不太理想,会把text的字段分成一个一个汉字,然后搜索的时候也会把搜索的句子进行分词,所以这里就需要更加智能的分词器IK分词器了. 1. i ...

  9. elasticsearch 5.6.4自动创建索引与mapping映射关系 +Java语言

    由于业务上的需求 ,最近在研究elasticsearch的相关知识 ,在网上查略了大部分资料 ,基本上对elasticsearch的数据增删改都没有太大问题 ,这里就不做总结了  .但是,在网上始终没 ...

随机推荐

  1. Team Work Ⅲ

    Regal-Lighting团队设计 分工思考 本次大作业我的分工定位是:Unit及子类,主要设计实现建筑类的功能. 在上一篇博客我介绍了我的继承方案和接口设定,这一篇粗略的介绍一下实现部分 Defe ...

  2. 第八次作业(课堂实战)- 项目UML设计

    本次作业博客 团队信息 队名:起床一起肝活队 原组长: 白晨曦(101) 原组员: 李麒 (123) 陈德斌(104) 何裕捷(214) 黄培鑫(217) 王焕仁(233) 林志华(128) 乐忠豪( ...

  3. SELECT - OVER 子句 (Transact-SQL)

    标题:SELECT - OVER 子句 (Transact-SQL) 地址:https://docs.microsoft.com/zh-cn/sql/t-sql/queries/select-over ...

  4. lintcode-248-统计比给定整数小的数的个数

    248-统计比给定整数小的数的个数 给定一个整数数组 (下标由 0 到 n-1,其中 n 表示数组的规模,数值范围由 0 到 10000),以及一个 查询列表.对于每一个查询,将会给你一个整数,请你返 ...

  5. PAT 甲级 1127 ZigZagging on a Tree

    https://pintia.cn/problem-sets/994805342720868352/problems/994805349394006016 Suppose that all the k ...

  6. 【Linux笔记】Linux中inittab剖析

    Linux完成内核(Kernel)引导后,会由init初始化进程调用/etc/inittab配置文件(ps -aux | less,init进程号为始终为1,是所有系统进程的起点,init进程也有一个 ...

  7. 第200天:js---常用string原型扩展

    一.常用string原型扩展 1.在字符串末尾追加字符串 /** 在字符串末尾追加字符串 **/ String.prototype.append = function (str) { return t ...

  8. 【bzoj4321】queue2 dp

    题目描述 n 个沙茶,被编号 1~n.排完队之后,每个沙茶希望,自己的相邻的两人只要无一个人的编号和自己的编号相差为 1(+1 或-1)就行:  现在想知道,存在多少方案满足沙茶们如此不苛刻的条件.  ...

  9. poj1958——Strange Towers of Hanoi

    The teacher points to the blackboard (Fig. 4) and says: "So here is the problem: There are thre ...

  10. NOI2014魔法森林题解报告

    题目描述 为了得到书法大家的真传,小 E 同学下定决心去拜访住在魔法森林中的隐 士.魔法森林可以被看成一个包含 n 个节点 m 条边的无向图,节点标号为 1,2,3,-,n,边标号为 1,2,3,-, ...