Elasticsearch学习笔记 -- 1

时间:2022-07-25
本文章向大家介绍Elasticsearch学习笔记 -- 1,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。

具体的大家可以再去网上看看介绍。这里就不阐述了

Elasticsearch

安装

笔者这里是使用docker安装的,比较方便。笔者使用docker-compose搭建了一个集群,并且安装了head插件。

  1. docker-compose.yml内容为
version: '3'
services:
  elasticsearch-master:
    restart: always
    image: elasticsearch:latest
    ports:
      - "9200:9200"
      - "9300:9300"
    environment:
      - ES_JAVA_OPTS=-Xms512m -Xmx512m
    volumes:
      - ./master-config:/usr/share/elasticsearch/config
    

  elasticsearch-slave1:
    restart: always
    image: elasticsearch:latest
    ports:
      - "8200:9200"
      - "8300:9300"
    depends_on:
      - elasticsearch-master
    links:
      - elasticsearch-master
    environment:
      - ES_JAVA_OPTS=-Xms512m -Xmx512m
      - discovery.zen.ping.unicast.hosts=lasticsearch-master
    volumes:
      - ./slave1-config:/usr/share/elasticsearch/config

  elasticsearch-head:
    restart: always
    image: mobz/elasticsearch-head:5
    ports:
      - "9100:9100"

具体的我会放到github上,如果想使用只要clone下来进入docker-start目录执行

$ docker-compose up -d

即可,如果没安装dockerdocker-compose,请自行搜索安装。

注:

  • 如果不搭建集群可以直接docker run,但是测试发现如果单结点运行在插入索引的时候,健康状态会变成yellow,
  • 随从结点可以不开启http,可以根据自己需要编写elasticsearch.yml
  • 第一次创建完容器之后,下次启动需要进入docker-compose.yml所在的文件路径执行docker-compose start即可。

测试是否成功

  1. 在浏览器输入127.0.0.1:9100,进入head插件的web端查看
  2. 还可以直接输入127.0.0.1:9200,查看相应结点的状态

根据提示,判断是否成功,如果你使用我的docker配置文件,除非端口冲突,一般是不会出错的。

elasticsearch基本操作

es的api基本格式为:http://:/<索引>/<类型>/<文档id>

使用http动词来操作数据

创建索引

  1. 非结构化创建索引 PUT /people

people为索引名

  1. 结构化创建索引 POST /book/novel/_mappings
{
  "novel": {
    "properties": {
      "title": {
        "type": "text"
      }
    }
  }
}

执行创建结构化时,索引必须存在,即执行上述命令时,book索引必须存在

如果索引不存在,使用下面的方式

PUT /people

{
	"settings":{
		"number_of_shards":3,   
		"number_of_replicas": 1
	},
	"mappings":{
		"man":{
			"properties":{
				"name":{
					"type": "text"
				},
				"country":{
					"type": "keyword"
				},
				"age":{
					"type": "integer"
				},
				"date":{
					"type":"date",
					"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
				}
			}
		},
		"woman":{
		}
	}
}
  • settings为当前索引的配置,比如切片数备份数
  • es支持||代表当前属性支持多种格式

数据插入

  1. 指定文档id插入

PUT /people/man/1

{
	"name":"earthchen",
	"country": "China",
	"age": 18,
	"date":"1996-11-25"
}
  1. 自动生成id插入

POST /people/man

{
	"name":"earthchen2",
	"country": "China",
	"age": 20,
	"date":"1997-11-25"
}

数据修改

  1. 直接修改

POST /people/man/1/_update

{
	"doc":{
		"name":"修改后的name"
	}
}
  1. 使用脚本

POST /people/man/1/_update

{
	"script":{
		"lang":"painless",
		"inline":"ctx._source.age=params.age",
		"params":{
			"age":100
		}
	}
}

或
{
	"script":{
		"lang":"painless",
		"inline":"ctx._source.age+=10",
	}
}

数据删除

  1. 删除指定的文档

DELETE /people/man/1

  1. 删除指定索引

DELETE /people

基本查询

查询结构为

{
    "mappings": {
        "novel": {
        "properties": {
            "word_count": {
                "type": "integer"
                },
            "author": {
                "type": "keyword"
                },
            "title": {
                "type": "text"
                },
            "publish_date": {
                "format": "yyyy-MM-dd HH:mm:ss || yyyy-MM-dd || epoch_millis",
                "type": "date"
        }
    }
}
简单查询
  1. 根据id查询数据

GET /book/novel/2

条件查询
  1. 查询所有数据

POST /book/_search

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

默认10条数据

  1. 指定从第几条返回,返回多少条数据

POST /book/_search

{
	"query":{
		"match_all":{}
	},
	"from":1,
	"size":2
}
  1. 查询关键词
    • 查询title中含有title的数据
{
    "query":{
        "match":{
            "title":"title"
        }
    }
}
{
    "query":{
        "match":{
            "title":"title4"
        }
    },
    "sort":[
            {
                "publish_date":{
                    "order":"desc"
                }
            }
        ]
}
聚合查询
  1. 按照指定字段聚合查询

POST /book/_search

{
	"aggs":{
		"group_by_word_count":{
			"terms":{
				"field":"word_count"
			}
		},
		"group_by_publish_date":{
			"terms":{
				"field":"publish_date"
			}
		}
	}
}
  1. 按照指定字段聚合计算

POST /book/_search

{
	"aggs":{
		"grades_word_count":{
			"stats":{
				"field":"word_count"
			}
		}
	}
}

高级查询

子条件查询(特定字段查询所指特定值)
  1. Query context

(在查询过程中,除了判断文档是否满足查询条件,es还会计算一个_score,来标示匹配的程度,为了判断目标文档和查询条件有多好)

  • 全文本查询(针对文本类型数据)
    1. 模糊匹配(分词匹配)match 查询title中含有elasticsearch或者入门的数据 POST /book/_search
{
    "query":{
        "match":{
            "title":"elasticsearch入门"
        }
    }
}
{
    "query":{
        "match_phrase":{
            "title":"elasticsearch学习"
        }
    }
}
{
    "query":{
        "multi_match":{
            "query":"elasticsearch",
            "fields":["title","author"]
        }
    }
}
{
    "query":{
        "query_string":{
            "query": "(elasticsearch AND 学习) OR java"
        }
    }
}
{
    "query":{
        "query_string":{
            "query": "(elasticsearch AND 学习) OR java OR 4444",
            "fields":["author","title"]
            
        }
    }
}
  • 字段级别查询(针对结构化数据,数字,日期等)term
    1. 对指定字段的精确查询
      1. 查询word_count等于1000的的数据 POST /book/_search
{
    "query":{
        "term":{
            "word_count": 1000
        }
    }
}
 {
 "query":{
        "range":{
            "word_count":{
                "lte": 3000,
                "gte":1000
            }
        }
    }
}
  1. Filter context (在查询过程中,只判断该文档是否满足条件,只有yes或者no,并且会缓存结果) 查询出word_count等于1000的数据
{
    "query":{
        "bool":{
            "filter":{
                "term":{
                    "word_count":1000
                }
            }
        }
    }
}
复合条件查询(以一定的逻辑组合子条件查询)
  1. 固定分数查询 查询所有索引中title为java POST /_search
{
    "query":{
        "constant_score":{
            "filter":{
                "match":{
                    "title": "java"
                }
            },
            "boost":2
        }
    }
}
  1. 布尔查询
    1. 查询所有索引中authoraaatitleelasticsearchshould) POST /_search
{
    "query":{
        "bool":{
            "should":[
                {
                    "match":{
                        "auther":"aaa"
                    }
                },
                {
                    "match":{
                        "title": "elasticsearch"
                    }
                }
            ]
        }
    }
}
{
    "query":{
        "bool":{
            "must":[
                {
                    "match":{
                        "author":"aaa"
                    }
                },
                {
                    "match":{
                        "title": "java"
                    }
                }
            ]
        }
    }
}
{
    "query":{
        "bool":{
            "must":[
                {
                    "match":{
                        "author":"aaa"
                    }
                },
                {
                    "match":{
                        "title": "java"
                    }
                }
            ],
            "filter":{
                "term":{
                    "word_count": 1000
                }
            }
        }
    }
}
{
    "query":{
        "bool":{
            "must_not":[
                {
                    "match":{
                        "author":"aaa"
                    }
                },
                {
                    "match":{
                        "title": "java"
                    }
                }
            ]
        }
    }
}

spring boot 使用es

集成es

1.在pom.xml中添加依赖。(es的依赖必须与你的es版本相对应,自行查看es版本 es内部使用log4j2作为日志,所以还需要添加log4j依赖)

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <elasticsearch.version>5.6.7</elasticsearch.version>
        <log4j-api.version>2.8.2</log4j-api.version>
        <log4j-core.version>2.7</log4j-core.version>
    </properties>

    <dependencies>

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

        <!--elasticsearch 客户端-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <!--ElasticSearch 5.x 根据官网配置maven 依赖, 由于 5.0x的 jar 内部使用的 apache log4日志。-->
        <!--所以要配置额外的依赖支持 org.apache.logging.log4j。-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j-core.version}</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  1. 添加log4j2的配置文件 在resources中创建文件log4j2.properties
appender.console.type=Console
appender.console.name=Console
appender.console.layout.type=PatternLayout
appender.console.layout.pattern=[%t] %-5p $c -%m%n
rootLogger.level=info
rootLogger.appenderRef.console.ref=console

笔者这里只配置了控制台的,如果还需要其他的自行配置一下。

对es进行操作

在需要的地方注入TransportClient,进行操作即可。具体内容这里就不贴出来了,github上有源码可以自己看看。

注: