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. Sqlserver学习研究

    关注关键词 :Sqlserver实用工具配置步骤 1)创建实用工具控制点(UCP) 2)连接到现有UCP 3)相UCP注册SQL Server实例 4)创建数据层应用程序 5)设置资源运行状况策略 6 ...

  2. lintcode-427-生成括号

    427-生成括号 给定 n 对括号,请写一个函数以将其生成新的括号组合,并返回所有组合结果. 样例 给定 n = 3, 可生成的组合如下: "((()))", "(()( ...

  3. SQL 语句(增删改查)

    一.增:有4种方法1.使用insert插入单行数据: --语法:insert [into] <表名> [列名] values <列值> 例:insert into Strden ...

  4. error CS0234: 命名空间“System.Drawing”中不存在类型或命名空间名称“Image”(是否缺少程序集引用?)

  5. pixi.js tools

    pixi群 881784250 Awesome pixi.js tools A list of useful libs/resources/tools for renowned html5 rende ...

  6. Distributed transactions in Spring, with and without XA

    While it's common to use the Java Transaction API and the XA protocol for distributed transactions i ...

  7. elsarticle模板 去掉摘要前后的两条横线

    参考:http://www.newsmth.net/nForum/#!article/TeX/316697?au=ericfire 如图:使用elsarticle模板修改PDF格式,去掉摘要前后的横线 ...

  8. hbase 安装笔记

    1.安装 在官方镜像站点下载hbase2.0,地址:https://www.apache.org/dyn/closer.lua/hbase/ 解压tar xzvf hbase-2.0.4-bin.ta ...

  9. [FJWC2018]全排列 DP

    题面 题面 题解 (表示第一段文字导致我在考场上没看懂题--因为我以为这个定义是定义在整个排列上的,所以相似 = 相同.结果其实是可以应用在一个区间上--) 首先我们发现,2个区间相似,其实就是离散化 ...

  10. Spring Boot系列教程三:使用devtools实现热部署

    一.前言 Eclipse下使用spring-tool-suite插件创建一个spring boot 工程,通过右键“Run As”--->"Spring Boot App"来 ...