1.认识ElasticSearch
Elasticsearch 是一个分布式的、开源的搜索分析引擎,支持各种数据类型,包括文本、数字、地理、结构化、非结构化。Elasticsearch 是基于 Apache Lucene 的。Elasticsearch 因其简单的 REST API、分布式特性、告诉、可扩展而闻名。Elasticsearch 是 Elastic 产品栈的核心,Elastic 产品栈是个开源工具集合,用于数据接收、存储、分析、可视化。
看不懂是吧
本人理解就是:我们输入的是模糊的字句,想在数据量庞大的库中查询查询,使用MySql的模糊查询like,是不太能实现的,所以ElasticSearch就是对like模糊查询的升级,它可以将我们输入的字句进行自动分词,转换为有一定结构的数据.
2.ElasticSearch的优势
2.1 那肯定是查询效率高 ! 查询效率高 ! 查询效率高 !
2.2 关键字可以实现高亮
为什么查询效率高呢?
1.e s 采用的是倒排索引 如图:
我们有①三段语句,分词器将语句中的所有词汇分割出来并记录上索引②, ③是将词汇转为全小写,④
是将词汇根据首字母顺序进行排序 ,⑤再将同样的词汇进行汇总并对应的语句
我们如果需要查询 ' java' ,就不会像MySql的like一样每个语句去逐字查询,es就可以直接根据java词汇所对应的语句索引查询, 这速度简直快的不是一星半点
3.常见的全文搜索
-
全文搜索工具包-Lucene(核心)
-
全文搜索服务器 ,Elastic Search(ES) / Solr等封装了lucene并扩展
4.springboot使用es代码
1.导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2.写入工具类 --可以直接拿去用,注意IP和端口就行
public class ESClientUtil {
public static TransportClient getClient(){
TransportClient client = null;
Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
try {
client = new PreBuiltTransportClient(settings).addTransportAddress(
new TransportAddress(InetAddress.getByName("127.0.0.1"), 9200));
} catch (UnknownHostException e) {
e.printStackTrace();
}
return client;
}
}
3.配置yml
spring:
elasticsearch:
rest:
uris:
- http://localhost:9200
4.domain对象
//indexName 索引库
//type 类型
//data 小辣椒
@Document(indexName = "orders",type = "_doc")//标记该对象是ES的文档对象
@Data
public class OrderDoc {
//标记为文档ID,该ID的值会作为document的id值
@Id
private Long id;
/**
* 需要分词的话需要指定,为text即使用分词 这里使用的是IK分词器
* 一般需要作为关键字搜索的字段都要指定为text,因为需要分词且创建索引
* type 指定的类型
*/
@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
//@Field(type = FieldType.Keyword)
private String name;
@Field(type = FieldType.Integer)
private int year;
@Field(type = FieldType.Double)
private BigDecimal salary;
}
5.创建Repository
/**
*ElasticsearchRepository 来操作ES,该接口中包含了针对ES的CRUD方法
* 注意泛型选择是那个domain对象有以及id类型
* /
@Repository
public interface OrderRepository extends ElasticsearchRepository<OrderDoc,Long> {
}
6.springboot测试 --注意修改方法就是添加,添加的时候如果id存在就执行修改
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SearchStart.class)
public class OrderESTest {
//操作ES的template模板
@Autowired
private ElasticsearchRestTemplate template;
@Autowired
private OrderRepository orderRepository;
@Test
public void test(){
//创建索引
Boolean bool1 = template.createIndex(CourseDoc.class);
System.out.println(bool);
//创建映射
Boolean boo2 = template.putMapping(CourseDoc.class);
System.out.println(boo2);
//添加
orderRepository.save(new OrderDoc(1L,"tom",2,new BigDecimal("2000")));
//根据id查询
Optional<OrderDoc> optional = orderRepository.findById(1l);
//根据id删除
orderRepository.deleteById(1L);
}
}