ElasticSearch学习笔记
一、在本地(或服务器)上安装ES和中文分词插件ik
MacOS 环境,直接使用homebrew安装
1
| brew install elasticsearch
|
安装中文分词插件ik
从github上下载源码并用mvn打包
1 2 3 4 5
| git clone https://github.com/medcl/elasticsearch-analysis-ik cd elasticsearch-analysis-ik mvn clean mvn compile mvn package
|
找到target中release里的压缩包,解压后放到es所在的安装包中的plugin/ik中。
(Mac中用homebrew安装的默认路径为/usr/local/Cellar)
注意:插件的版本必须和ES相匹配。
二、elasticsearch基本概念
- Elastic 本质上是一个分布式数据库,允许多台服务器协同工作,每台服务器可以运行多个 Elastic 实例。
单个 Elastic 实例称为一个节点(node)。一组节点构成一个集群(cluster)。
Document 使用 JSON 格式表示。
MySQL |
Elasticsearch |
Database |
Index |
Table |
Type |
Row |
Document |
Column |
Field |
Schema |
Mappping |
Index |
Everything Indexed by default |
SQL |
Query DSL |
二、安装elasticsearch.js
直接使用npm
1
| npm install elasticsearch.js --save
|
三、调用接口
1.实例化client
1 2 3 4 5
| const elasticsearch = require('elasticsearch'); const client = new elasticsearch.Client({ host: '127.0.0.1:9200', log: 'trace' });
|
2.创建index
1
| client.indices.create({index : 'test'});
|
3.创建mapping
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| client.indices.putMapping({ index : 'test', type : 'article', body : { article: { properties: { title: { type: 'string', term_vector: 'with_positions_offsets', analyzer: 'ik', search_analyzer: 'ik', }, content: { type: 'string', term_vector: 'with_positions_offsets', analyzer: 'ik', search_analyzer: 'ik', }, slug: { type: 'string', }, tags: { type: 'string', index : 'not_analyzed', }, update_date: { type : 'date', index : 'not_analyzed', } } } } });
|
4.调入测试数据
1 2 3 4 5 6 7 8 9 10 11 12
| client.index({ index : 'test', type : 'article', id : '100', body : { title : '什么是 JS?', slug :'what-is-js', tags : ['JS', 'JavaScript', 'TEST'], content : 'JS 是 JavaScript 的缩写!', update_date : '2018-1-7T13:05:55Z', } })
|
5.搜索测试
1 2 3 4 5
| client.search({ index : 'test', type : 'article', q : 'JS', });
|
6.详细匹配
1 2 3 4 5 6 7 8 9 10 11 12 13
| client.search({ index: 'test', body: { query: { match: { title: 'JS', content: '搜索' } } } }, function (error, response) { });
|
ES支持一种JSON格式的查询,叫做DSL,domain specific language。