"type": "keyword",
"index": false
},
"price": {
"type": "integer"
},
"score": {
"type": "integer"
},
"brand": {
"type": "keyword",
"copy\_to": "all"
},
"city": {
"type": "keyword"
},
"starName": {
"type": "keyword"
},
"business": {
"type": "keyword",
"copy\_to": "all"
},
"location": {
"type": "geo\_point"
},
"pic": {
"type": "keyword",
"index": false
},
"all": {
"type": "text",
"analyzer": "ik\_max\_word"
}
}
}
}
基于elasticsearch的规则, id用keyword
* 操作索引库
import com.zyw.elasticsearchdemo.constants.HotelConstants;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class ElasticsearchDemoApplicationTests {
private RestHighLevelClient client;
/\*\*
* 删除索引库
*/
@Test
void deleteHotelIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest(“hotel”);
client.indices().delete(request, RequestOptions.DEFAULT);
}
/\*\*
* 判断索引库是否存在
*/
@Test
void existHotelIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest(“hotel”);
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists ? “索引库已经存在” : “索引库不存在”);
}
/\*\*
* 创建索引库
*/
@Test
void createHotelIndex() throws IOException {
// 1.创建request对象
CreateIndexRequest request = new CreateIndexRequest(“hotel”);
// 2.准备请求的参数, DSL语句
request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);
// 3. 发送请求
client.indices().create(request, RequestOptions.DEFAULT);
}
@BeforeEach
void setUp() {
this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://82.114.174.50:9200")));
}
@AfterEach
void tearDown() throws IOException {
client.close();
}
}
## RestClient操作文档
---
import cn.hutool.json.JSONUtil;
import com.zyw.elasticsearchdemo.mapper.HotelMapper;
import com.zyw.elasticsearchdemo.pojo.Hotel;
import com.zyw.elasticsearchdemo.pojo.HotelDoc;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.List;
@SpringBootTest
public class ElasticsearchDemoApplicationTests1 {
private RestHighLevelClient client;
@Autowired
private HotelMapper hotelMapper;
/\*\*
* 删除文档
*/
@Test
void deleteDocument() throws IOException {
DeleteRequest request = new DeleteRequest(“hotel”, “200216665”);
client.delete(request, RequestOptions.DEFAULT);
}
/\*\*
* 修改文档-局部更新, 全量和创建一样
*/
@Test
void updateDocument() throws IOException {
UpdateRequest request = new UpdateRequest(“hotel”, “200216665”);
request.doc(“price”, 2600, “starName”, “六钻”);
client.update(request, RequestOptions.DEFAULT);
}
/\*\*
* 查询文档
*/
@Test
void getDocument() throws IOException {
// 准备request对象
GetRequest request = new GetRequest(“hotel”, “200216665”);
// 发送请求
GetResponse response = client.get(request, RequestOptions.DEFAULT);
String json = response.getSourceAsString();
HotelDoc hotelDoc = JSONUtil.toBean(json, HotelDoc.class);
System.out.println(hotelDoc);
}
/\*\*
* 新增文档
*/
@Test
void addDocument() throws IOException {
// 根据id查询酒店数据
Hotel hotel = hotelMapper.selectById(200216665);
// 转换为文档对象
HotelDoc hotelDoc = new HotelDoc(hotel);
// 准备request对象
IndexRequest request = new IndexRequest(“hotel”).id(hotel.getId().toString());
// 准备json文档
request.source(JSONUtil.toJsonStr(hotelDoc), XContentType.JSON);
// 发送请求
client.index(request, RequestOptions.DEFAULT);
}
/\*\*
* 批量导入文档
*/
@Test
void batchAddDocument() throws IOException {
List hotels = hotelMapper.selectList(null);
BulkRequest request = new BulkRequest();
for (Hotel hotel : hotels) {
HotelDoc hotelDoc = new HotelDoc(hotel);
request.add(new IndexRequest(“hotel”).id(hotelDoc.getId().toString())
.source(JSONUtil.toJsonStr(hotelDoc), XContentType.JSON));
}
// 发送
client.bulk(request, RequestOptions.DEFAULT);
}
@BeforeEach
void setUp() {
this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://82.114.174.50:9200")));
}
@AfterEach
void tearDown() throws IOException {
client.close();
}
}
## DSL查询语法
---
### 分类和基本语法
#### 全文检索查询
全文检索查询, 会对用户输入内容分词, 常用于搜索框搜索
建议把多个字段copy到一个字段里
#### 精确查询
#### 地理查询
#### 复合查询
* 复合(compound)查询: 复合查询可以将其他简单查询组合起来, 实现更复杂的搜索逻辑.
+ `function score`: 复分函数查询, 可以控制文档相关性算分, 控制文档排名. 例如百度竞价
## 搜索结果处理
---
### 排序
### 分页
### 高亮
默认字段要一致, 可以用`require_field_match` 取消一致
## RestClient查询文档–高级查询
---
import cn.hutool.json.JSONUtil;
import com.zyw.elasticsearchdemo.pojo.HotelDoc;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Map;
public class QueryDocumentTest {
private RestHighLevelClient client;
/\*\*
* 广告置顶
*/
@Test
void adScore() throws IOException {
SearchRequest request = new SearchRequest(“hotel”);
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.termQuery(“city”, “上海”));
// 算分控制
FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQuery, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery(“isAd”, true),
// 分数10
ScoreFunctionBuilders.weightFactorFunction(10))
}).boostMode(CombineFunction.SUM); // 用加法 --> 分数+10
request.source().query(functionScoreQuery);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
handleResponse(response);
}
/\*\*
* 高亮
*/
@Test
void testHighlight() throws IOException {
SearchRequest request = new SearchRequest(“hotel”);
request.source().query(QueryBuilders.matchQuery(“all”, “维也纳”));
// 高亮设置
request.source().highlighter(new HighlightBuilder().field(“name”).requireFieldMatch(false));
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
handleResponse(response);
}
/\*\*
* 排序和分页
*/
@Test
void sortAndPage() throws IOException {
SearchRequest request = new SearchRequest(“hotel”);
request.source().sort(“price”, SortOrder.ASC).from(20).size(5);
request.source().query(QueryBuilders.matchAllQuery());
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
handleResponse(response);
}
/\*\*
* 根据地理坐标排序
*/
@Test
void sortByLocation() throws IOException {
SearchRequest request = new SearchRequest(“hotel”);
request.source().sort(SortBuilders.geoDistanceSort(“location”,
// 坐标字符串前面是纬度,后面是经度
new GeoPoint(“31.21, 121.5”)).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
request.source().query(QueryBuilders.matchQuery(“all”, “如家”));
// 高亮设置
request.source().highlighter(new HighlightBuilder().field(“name”).requireFieldMatch(false));
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
handleResponse(response);
}
/\*\*
* bool查询
* @throws IOException
*/
@Test
void testBool() throws IOException {
SearchRequest request = new SearchRequest(“hotel”);
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
// 添加term
boolQuery.must(QueryBuilders.termQuery(“city”, “上海”));
// 添加range
boolQuery.filter(QueryBuilders.rangeQuery(“price”).lte(500));
request.source().query(boolQuery);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
handleResponse(response);
}
/\*\*
* bool查询 --should
* @throws IOException
*/
@Test
void testBool() throws IOException {
SearchRequest request = new SearchRequest(“hotel”);
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
BoolQueryBuilder shouldQuery = QueryBuilders.boolQuery();
shouldQuery.should(QueryBuilders.matchQuery(“name”, “上海”)).should(QueryBuilders.matchQuery(“name”,“北京”));
shouldQuery.minimumShouldMatch(1); // name中有上海或者北京,满足一个
boolQuery.must(shouldQuery);
// 添加range
boolQuery.filter(QueryBuilders.rangeQuery(“price”).lte(180));
request.source().query(boolQuery);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
handleResponse(response);
}
/\*\*
* match查询
*/
@Test
void testMatch() throws IOException {
SearchRequest request = new SearchRequest(“hotel”);
request.source().query(QueryBuilders.matchQuery(“all”, “如家”));
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
handleResponse(response);
}
/\*\*
* 处理结果
* @param response
*/
private static void handleResponse(SearchResponse response) {
SearchHits searchHits = response.getHits();
// 查询的总条数
long total = searchHits.getTotalHits().value;
System.out.println("total = " + total);
// 查询的结果数组
SearchHit[] hits = searchHits.getHits();
for (SearchHit hit : hits) {
// 得到source
String json = hit.getSourceAsString();
HotelDoc hotelDoc = JSONUtil.toBean(json, HotelDoc.class);
// 获取高亮结果
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
if(!highlightFields.isEmpty()){
// 根据字段名获取高亮结果
HighlightField highlightField = highlightFields.get(“name”);
// 获取高亮值
String name = highlightField.getFragments()[0].toString();
// 覆盖非高亮结果
hotelDoc.setName(name);
}
// 获取location距离排序值 --> 距离4.5km
Object[] sortValues = hit.getSortValues();
if (sortValues.length != 0) {
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Linux运维工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Linux运维全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Linux运维知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以添加VX:vip1024b (备注Linux运维获取)
最后的话
最近很多小伙伴找我要Linux学习资料,于是我翻箱倒柜,整理了一些优质资源,涵盖视频、电子书、PPT等共享给大家!
资料预览
给大家整理的视频资料:
给大家整理的电子书资料:
如果本文对你有帮助,欢迎点赞、收藏、转发给朋友,让我有持续创作的动力!文章来源:https://www.toymoban.com/news/detail-854493.html
一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新**
如果你觉得这些内容对你有帮助,可以添加VX:vip1024b (备注Linux运维获取)
[外链图片转存中…(img-p8iNszVY-1712497682353)]
最后的话
最近很多小伙伴找我要Linux学习资料,于是我翻箱倒柜,整理了一些优质资源,涵盖视频、电子书、PPT等共享给大家!
资料预览
给大家整理的视频资料:
[外链图片转存中…(img-YmrctqjR-1712497682353)]
给大家整理的电子书资料:
[外链图片转存中…(img-oMK0Ch9E-1712497682353)]
如果本文对你有帮助,欢迎点赞、收藏、转发给朋友,让我有持续创作的动力!
一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
[外链图片转存中…(img-TaESOOm4-1712497682354)]文章来源地址https://www.toymoban.com/news/detail-854493.html
到了这里,关于javaAPI操作Elasticsearch_elasticsearch 修改字段 java api的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!