整体概述
Elasticsearch是依托于Lucene开发出来的检索引擎,Lucene是一个Full Text搜索库(也有很多其他形式的搜索库)
图解
图解 Elasticsearch

Elasticsearch由多个Index组成

Index可分为多个Shard

一个
Shard本质上是一个Lucene Index,Lucene Index内部由大小不一的多个Segment组成
图解 Lucene
Segment内部(有多种不同的数据结构)
Inverted IndexStored FieldsDocument ValuesCache
1. Inverted Index
举例输入:
{"id":1,"words":"Winter is coming."}
{"id":2,"words":"The choice is yours."}
|-------Inverted Index------|
| Dictionary | Postings |
| term | flag | documents |
| winter | 1 | 1 |
| is | 2 | 1,2 |
| coming | 1 | 1 |
| the | 1 | 2 |
| choice | 1 | 2 |
| yours | 1 | 2 |
Inverted Index主要包括两部分:
- 一个有序的数据字典
Dictionary(包括单词Term和它出现的频率)。 - 与单词
Term对应的Postings(即存在这个单词的文件)。
当我们搜索的时候,首先将搜索的内容分解,然后在字典里找到对应Term,从而查找到与搜索相关的文件内容。
2. Stored Fields
当我们想要查找包含某个特定标题内容的文件时,Inverted Index就不能很好的解决这个问题,所以Lucene提供了另外一种数据结构Stored Fields来解决这个问题。本质上,Stored Fields是一个简单的键值对key-value。默认情况下,ElasticSearch会存储整个文件的JSON source。
举例输入:
{"id":1,"words":"Winter is coming."}
{"id":2,"words":"The choice is yours."}
Stored Fields:
_source = {"id":1,"words":"Winter is coming."}
_source = {"id":2,"words":"The choice is yours."}
3. Document Values
即使这样,我们发现以上结构仍然无法解决诸如:排序、聚合、facet,因为我们可能会要读取大量不需要的信息。所以,另一种数据结构解决了此种问题:Document Values。这种结构本质上就是一个列式的存储,它高度优化了具有相同类型的数据的存储结构。
举例输入:
{"code":"1001","bank_name":"ICBC","balance":30000}
{"code":"1002","bank_name":"CMBC","balance":50000}

为了提高效率,ElasticSearch可以将索引下某一个Document Value全部读取到内存中进行操作,这大大提升访问速度,但是也同时会消耗掉大量的内存空间。
总之,这些数据结构Inverted Index、Stored Fields、Document Values及其cache,都在segment内部。