Java使用强大的Elastisearch搜索引擎实例代码
时间:2019-03-30
本文章向大家介绍Java使用强大的Elastisearch搜索引擎实例代码,主要包括Java使用强大的Elastisearch搜索引擎实例代码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
Elastisearch是一个很强大,易用的搜索引擎
在系统上运行Elastisearch只需以下几步
1.下载Elastisearch
复制代码 代码如下:
2.解压
unzip elasticsearch-5.4.0.zip
3.运行
elasticsearch-5.4.0/bin/elasticsearch
这时有可能会直接被Killed掉,因为内存溢出(OOM),elastisearch占用的内存非常大,所以在内存比较小的服务器上运行要先修改jvm的内存大小
vi elasticsearch-5.4.0/config/jvm.options
将22和23行的栈堆大小改为512M
-Xms512M -Xmx512M
如果重新启动后还是killed就再改小一点
4.测试是否成功
curl 'http://localhost:9200/?pretty'
你能看到以下返回信息:
{ "status": 200, "name": "Shrunken Bones", "version": { "number": "1.4.0", "lucene_version": "4.10" }, "tagline": "You Know, for Search" }
则表明启动成功
接下来我们用Java的API来操作Elasticsearch
首先是导入elastisearch和log4j的包
POM
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jk</groupId> <artifactId>ElasticsearchExample</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <!--用哪个版本就填什么--> <version>5.4.0</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.7</version> </dependency> </dependencies> </project>
以下是常用的几种操作
1.创建client
Client client = null; try { client = new PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); } catch (Exception e) { e.printStackTrace(); }
2.创建索引
/** * 创建索引,有则先删除 * @param client */ private static void recreateIndex(Client client) { if (client.admin().indices().prepareExists(index).execute().actionGet() .isExists()) { DeleteIndexResponse deleteIndexResponse = client.admin().indices() .delete(new DeleteIndexRequest(index)).actionGet(); System.out.println("delete index :"); System.out.println(deleteIndexResponse); } CreateIndexResponse createIndexResponse = client.admin().indices() .prepareCreate(index).execute().actionGet(); System.out.println("create index :"); System.out.println(createIndexResponse); }
3.插入数据
/** * 插入数据 * @param client */ @SuppressWarnings({"rawtypes", "unchecked"}) private static void doIndex(final Client client) { Map s11 = new LinkedHashMap(); s11.put("title", "Think in java"); s11.put("origin", "美国"); s11.put("description", "初级java开发人员必读的书"); s11.put("author", "Bruce Eckel"); s11.put("price", 108); Map s12 = new LinkedHashMap(); s12.put("title", "Head First Java"); s12.put("origin", "英国"); s12.put("description", "java入门教材"); s12.put("author", "Kathy Sierra"); s12.put("price", 54); Map s21 = new LinkedHashMap(); s21.put("title", "Design Pattern"); s21.put("origin", "法国"); s21.put("description", "程序员不得不读的设计模式"); s21.put("author", "Kathy Sierra"); s21.put("price", 89); Map s22 = new LinkedHashMap(); s22.put("title", "黑客与画家"); s22.put("origin", "法国"); s22.put("description", "读完之后脑洞大开"); s22.put("author", "Paul Graham"); s22.put("price", 35); BulkResponse bulkResponse = client .prepareBulk() .add(client.prepareIndex(index, type).setId("11").setSource(s11).setOpType(IndexRequest.OpType.INDEX).request()) .add(client.prepareIndex(index, type).setId("12").setSource(s12).setOpType(IndexRequest.OpType.INDEX).request()) .add(client.prepareIndex(index, type).setId("21").setSource(s21).setOpType(IndexRequest.OpType.INDEX).request()) .add(client.prepareIndex(index, type).setId("22").setSource(s22).setOpType(IndexRequest.OpType.INDEX).request()) .execute().actionGet(); if (bulkResponse.hasFailures()) { System.err.println("index docs ERROR:" + bulkResponse.buildFailureMessage()); } else { System.out.println("index docs SUCCESS:"); System.out.println(bulkResponse); } }
4.查询所有
/** * 查询所有 */ private static void searchAll(Client client) { SearchResponse response = client.prepareSearch(index) .setQuery(QueryBuilders.matchAllQuery()) .setExplain(true).execute().actionGet(); System.out.println("searchAll : "); for (SearchHit searchHit : response.getHits()) { System.out.println("********"); System.out.println(searchHit.getSource()); } }
5.关键词查询
/** * 关键词查询 * * @param client */ private static void searchKeyWord(Client client) { SearchResponse response = client.prepareSearch(index) //查询所有字段匹配关键字 .setQuery(QueryBuilders.matchQuery("_all", "法国")) //设置最小匹配程度 // .setQuery(QueryBuilders.matchQuery("_all", "法国").minimumShouldMatch("100%")) .execute().actionGet(); System.out.println("searchKeyWord : "); System.out.println(response); }
6.数值范围过滤
/** * 数值范围过滤 * * @param client */ private static void searchRange(Client client) { SearchResponse response = client.prepareSearch(index). //大于80,小于100 setQuery(QueryBuilders.rangeQuery("price").gt(80).lt(100)) .execute() .actionGet(); System.out.println("searchRange : "); System.out.println(response); }
7.排序
/** * 排序 * * @param client */ private static void searchOrdered(Client client) { SearchResponse response = client.prepareSearch(index) .setQuery(QueryBuilders.matchAllQuery()) //根据价格降序排序 .addSort(SortBuilders.fieldSort("price") .order(SortOrder.DESC)).execute().actionGet(); System.out.println("searchOrdered : "); System.out.println(response); }
8.高亮关键字
/** * 高亮关键字 * @param client */ private static void searchHightlight(Client client) { //高亮多个字段 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.field("title"); highlightBuilder.field("description"); SearchResponse response = client.prepareSearch(index) //单条件匹配,高亮时只能高亮该字段 // .setQuery(QueryBuilders.matchQuery("title", "java")) //多条件匹配,高亮时只能高亮多个字段 .setQuery(QueryBuilders.multiMatchQuery("开发人员必读", "title", "description")) .highlighter(highlightBuilder) .execute() .actionGet(); System.out.println("searchHightlight : "); System.out.println(response); }
9.根据id查找
/** * 根据id查找 * @param client */ private static void findById(final Client client) { String id="12"; GetResponse response = client.prepareGet(index, type, id).get(); System.out.println("findById"); System.out.println(response); }
10.删除
/** * 删除 * @param client */ private static void deleteById(Client client) { String id="12"; DeleteResponse response = client.prepareDelete(index, type, id).get(); }
11.更新
/** * 更新 * @param client */ private static void updateById(Client client) { try { String id="11"; client.prepareUpdate(index, type, id) .setDoc(jsonBuilder() .startObject() .field("title", "白鹿原") .endObject()) .get(); } catch (IOException e) { e.printStackTrace(); } }
常用的操作就这些,代码上传到https://github.com/jkgeekJack/ElasticsearchExample
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
- poj 1579 Function Run Fun
- React第三方组件2(状态管理之Refast的使用③扩展ctx)
- 财经小知识——CRS风暴与全球离岸金融中心
- The Triangle
- React第三方组件2(状态管理之Refast的使用②异步修改state)
- UVa Automatic Editing
- React第三方组件2(状态管理之Refast的使用①简单使用)
- uva Excuses, Excuses!
- React第三方组件5(状态管理之Redux的使用④TodoList下)
- 2017/6/9-Python文件读写的方法
- React第三方组件5(状态管理之Redux的使用③TodoList中)
- R语言在收入不平等指标测度上的应用~
- React第三方组件5(状态管理之Redux的使用②TodoList上)
- sscanf
- java教程
- Java快速入门
- Java 开发环境配置
- Java基本语法
- Java 对象和类
- Java 基本数据类型
- Java 变量类型
- Java 修饰符
- Java 运算符
- Java 循环结构
- Java 分支结构
- Java Number类
- Java Character类
- Java String类
- Java StringBuffer和StringBuilder类
- Java 数组
- Java 日期时间
- Java 正则表达式
- Java 方法
- Java 流(Stream)、文件(File)和IO
- Java 异常处理
- Java 继承
- Java 重写(Override)与重载(Overload)
- Java 多态
- Java 抽象类
- Java 封装
- Java 接口
- Java 包(package)
- Java 数据结构
- Java 集合框架
- Java 泛型
- Java 序列化
- Java 网络编程
- Java 发送邮件
- Java 多线程编程
- Java Applet基础
- Java 文档注释
- 【python实现卷积神经网络】开始训练
- django实战(五)--增加数据
- 实战django(一)--(你也能看懂的)注册与登录(带前端模板)
- 【python-leetcode23-多路归并】合并k个排序链表
- 实战django(二)--登录实现记住我
- org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.gong.mybatis.da
- 【python-leetcode378-二分查找】有序矩阵中的第k小元素
- 使用cookie来记录用户登录次数,为何次数不更新
- (二)golang--windows下vscode的安装以及go环境的配置
- mybatis文件映射之使用#取值时的一些规则
- 【论文笔记】Improved Residual Networks for Image and Video Recognition(ResNet新变体:IResNet)
- SQL语句在MYSQL中的运行过程和各个组件的介绍
- (五)golang--常用的一些玩意
- 关于MYSQL 的日志系统
- (六)golang--变量