ElasticSearch简单入门

  • Jesse
  • 2017-02-20 16:27:00
  • 3066
ElasticSearch(简称ES)是一个使用java开发并基于Lucene构建的开源、分布式、RESTful的全文本搜索引擎。 支持存储,查询,排序,分页等数据库的功能,数据存储在硬盘中。

ElasticSearch特点:

分布式的实时文件存储,每个字段都被索引并可被搜索

分布式的实时分析搜索引擎

可以扩展到上百台服务器,处理PB级结构化或非结构化数据

 

虽然存储的数据很大,但查询速度依然非常快,常用语日志分析和大数据检索

 

mysql对应关系:

索引(index)

类型(type)

 

 

1.elasticsearch之索引查询

 

官方手册:https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html

中文手册:https://es.xiaoleilu.com/

 

1>查询

UI界面:http://localhost:9200/_plugin/head/

 

空查询:

curl -XGET 'localhost:9200/students/_search?pretty'

 

索引总数:

http://10.1.10.191:9200/company/_count?pretty

 

模糊查询:

curl -XGET 'http://10.1.10.191:9200/cp/_search?pretty&q=张三'

 

elasticsearch精准查询

curl -XPOST 'http://10.1.10.191:9200/company/_query?pretty' -d
'{
  "query": {
    "bool": {
      "must": {
        "match_phrase": {
          "name": "深圳市腾讯计算机系统有限公司"
        }
      }
    }
  },
  "size": 20
}'

 

原始json

curl -XPOST 'http://10.1.10.191:9200/company/_query?pretty' -d'{"query": {"bool": {"must": {"match_phrase": "name": "深圳市腾讯计算机系统有限公司"}}}},"size": 10}'

 

2>删除

curl -XDELETE 'http://10.1.10.191:9200/company/_query?pretty' -d '{"query": {"bool": {"must": {"match_phrase": {"name": "深圳市腾讯计算机系统有限公司"}}}}}'


删除索引

curl -XDELETE http://10.1.10.191:9200/company


2.elasticsearch之数据导入

1>json文件导入

导入单条数据

 

指定索引id

curl -XPUT 'http://10.1.10.191:9200/company/account/20000012' -d '{ "name": "深圳市茅庐信息科技有限公司666"}'


不指定索引id,自动生成

curl -XPOST 'http://10.1.10.191:9200/company/account/' -d '{ "name": "深圳市茅庐信息科技有限公司888"}'


导入json数据

curl -XPOST localhost:9200/company/_bulk --data-binary @file.json


json文件格式:

https://raw.githubusercontent.com/elastic/elasticsearch/master/docs/src/test/resources/accounts.json

 

2>mysql导入

借助插件elasticsearch-jdbc,从mysql导入数据到ES

 

(1)选择elasticsearch对应的jdbc版本,安装到服务器

http://xbib.org/repository/org/xbib/elasticsearch/importer/elasticsearch-jdbc/

 

wget http://xbib.org/repository/org/xbib/elasticsearch/importer/elasticsearch-jdbc/1.7.1.0/elasticsearch-jdbc-1.7.1.0-dist.zip

(2)解压

unzip elasticsearch-jdbc-1.7.1.0-dist.zip  

 

(3)编写脚本导入

vim /usr/local/elasticsearch-jdbc-1.7.1.0/bin/import.sh

#!/bin/bash
set -e
bin=/usr/local/elasticsearch-jdbc-1.7.1.0/bin
lib=/usr/local/elasticsearch-jdbc-1.7.1.0/lib
echo '{
"type" : "jdbc",
"jdbc" : {
"url" : "jdbc:mysql://10.1.10.114:3306/database",
"user" : "root",
"password" : "123456",
"sql" : "select * from table;",
"index": "table",
"type": "name"
}
}' | java \
-cp "${lib}/*" \
-Dlog4j.configurationFile=${bin}/log4j2.xml \
org.xbib.tools.Runner \
org.xbib.tools.JDBCImporter

 

(4)赋给权限,执行

chmod +x import.sh
./import.sh