IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 大数据 -> 基于elasticSearch实现自动补全 基于 RestHighLevelClient -> 正文阅读

[大数据]基于elasticSearch实现自动补全 基于 RestHighLevelClient

基于elasticSearch实现自动补全 基于 RestHighLevelClient

基于elasticSearch实现自动补全
为什么要用es来实现?

因为能共用一个搜索服务,并且稳定,能利用已有的分词器。

有多少种实现方法?本文用的是哪一种?

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html

本文用的completion suggester 来实现的。

已经有那么多文章了,为何还要写?

很多文章没有及时更新
记录自己的理解
整体流程
添加索引,并单独写一个字节点用来实现自动补全,并设置类型为completion

 {
        "mappings": {
            "properties": {
                "fileName": {
                    "type": "text",
                    "analyzer": "ik_max_word",
                    "fields": {
                        "suggest": {
                            "type": "completion",
                            "analyzer": "ik_max_word"
                        }
                    }
                },
                "path": {
                    "type": "keyword",
                    "index": false
                }
            }
        }
    }

插入数据

POST /search_index/_doc
{
    "fileName":"四川成都市龙泉驿生态环境局龙泉驿区3D气溶胶雷达监控采购项目的中标公告"
}
POST /search_index/_doc
{
    "fileName":"气溶胶雷达租赁服务报价清单"
}
POST /search_index/_doc
{
    "fileName":"四川省遂宁市安居生态环境局臭氧在线监测预警系统采购项目竞争性磋商终止(废标)公告"
}
实现搜索补全
POST /search_index/_search
{
  "suggest": {
    "my_suggest_document": {
      "prefix": "四",
      "completion": {
        "field": "fileName.suggest"
      }
    }
  }
}

JAVA基于RestHighLevelClient客户端的实现
构建配置客户端连接

@Configuration
@EnableElasticsearchRepositories
public class ElasticsearchConfiguration extends AbstractElasticsearchConfiguration {


    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {

        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("192.168.15.207:9200")

                //.withConnectTimeout(Duration.ofSeconds(5))
                //.withSocketTimeout(Duration.ofSeconds(3))
                //.useSsl()
                //.withDefaultHeaders(defaultHeaders)
                //.withBasicAuth(username, password)
                // ... other options
                .build();
        return RestClients.create(clientConfiguration).rest();
    }

//    @Bean
//    public ElasticsearchRestTemplate restTemplate() throws Exception {
//        return new ElasticsearchRestTemplate(elasticsearchClient());
//    }

}

配置Java bean

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "search_index", type = "_doc", shards = 5, replicas = 1)
public class DocumentPo implements Serializable {
    private static final long serialVersionUID = 3433260756083989671L;
    @Id
    public String id;
    @Field(type = FieldType.Keyword)  
   // @Field(type = FieldType.Text, analyzer = "ik_max_word")
    public String fileName;   
    @Field(index = false, type = FieldType.Keyword)
    public String compassPath;

}

添加数据

public interface DocumentRepository extends ElasticsearchRepository<DocumentPo,Long> {
}

//添加
@Autowired
DocumentRepository documentRepository;

documentRepository.save(documentPo);
实现搜索

 @Autowired
    private RestHighLevelClient restHighLevelClient;

@RequestMapping(value = "/by_contact",method = RequestMethod.GET)
    public Object getSearchSuggest(HttpServletRequest request, @RequestParam(value = "keyWord")String keyWord)  {
        //指定在哪个字段搜索
        String suggestField = "fileName.suggest";
        SearchRequest searchRequest = new SearchRequest("search_index");
        searchRequest.types("_doc");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder qb = QueryBuilders.boolQuery();
        SuggestionBuilder termSuggestionBuilder =SuggestBuilders.completionSuggestion(suggestField).prefix(keyWord).skipDuplicates(true).size(10);
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        suggestBuilder.addSuggestion("my_suggest_document", termSuggestionBuilder );
        searchSourceBuilder.suggest(suggestBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = null;
        try {
            response = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        Suggest suggest = response.getSuggest();
        List<String> keywords = null;
        if (suggest != null) {
            keywords = new ArrayList<>();
            List<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> entries =
                    suggest.getSuggestion("my_suggest_document").getEntries();
            for (Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option> entry: entries) {
                for (Suggest.Suggestion.Entry.Option option: entry.getOptions()) {
                    String keyword = option.getText().string();
                    if (!StringUtils.isEmpty(keyword)) {
                        if (keywords.contains(keyword)) {
                            continue;
                        }
                        keywords.add(keyword);
                        if (keywords.size() >= 9) {
                            break;
                        }
                    }
                }
            }
        }
        return keywords;
    }

多个条件的搜索

 public SearchResponse autosuggestSearch() throws IOException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder qb = QueryBuilders.boolQuery();

        PrefixQueryBuilder namePQBuilder = QueryBuilders.prefixQuery("address", "usa");
        PrefixQueryBuilder addressPQBuilder = QueryBuilders.prefixQuery("address", "usa");
        qb.should(namePQBuilder);
        qb.should(addressPQBuilder); //Similarly add more fields prefix queries.
        sourceBuilder.query(qb);

        SearchRequest searchRequest = new SearchRequest("employee").source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println("Search JSON query \n" + searchRequest.source().toString()); //Generated ES search JSON.
        return searchResponse;
    }

参考网址

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-suggesters.html

https://stackoverflow.com/questions/60397369/elasticsearch-7-6-3-java-highlevel-rest-client-auto-suggest-across-multiple-fi

https://stackoverflow.com/questions/54399859/completion-suggester-in-elasticsearch-6-5-4-with-java-rest-client-api?answertab=votes#tab-top

https://stackoverflow.com/questions/48657904/how-to-write-rest-high-level-client-query-for-prefix-suggestion/50707641

https://blog.csdn.net/jonkee/article/details/115421810

  大数据 最新文章
实现Kafka至少消费一次
亚马逊云科技:还在苦于ETL?Zero ETL的时代
初探MapReduce
【SpringBoot框架篇】32.基于注解+redis实现
Elasticsearch:如何减少 Elasticsearch 集
Go redis操作
Redis面试题
专题五 Redis高并发场景
基于GBase8s和Calcite的多数据源查询
Redis——底层数据结构原理
上一篇文章      下一篇文章      查看所有文章
加:2021-08-26 12:10:28  更:2021-08-26 12:12:13 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 13:12:24-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码