开朗小哥 2022-09-01 11:19 采纳率: 100%
浏览 36
已结题

javaweb+elasticsearch全文检索+elasticsearch-rest-high-level-client

问题遇到的现象和发生背景

我在javaweb中使用了ajax,在AllHttpServlet中调用了search()方法,该方法中使用elasticsearch-rest-high-level-client实现全文检索,结果开启tomcat后导致其他的请求也失败了,tomcat报错在下面。
js:

    //搜索
        $.ajax({
            // url : 'http://192.168.1.134:80/BlogSystem/AllHttpServlet',
            url : 'http://localhost:8080/BlogSystem/AllHttpServlet',
            type : 'GET',
            dataType : 'json',
            xhrFields:{
                withCredentials:true //允许携带cookie
            },
            data:{
                id:"search",
                search_text:document.getElementsByName('searchtext')[0].value,
            },
            success:function(data){
                var arr = data["hits"]["hits"];
                alert(arr[0]);

search()方法:

    //搜索
    public static void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        try {
            String search_text = request.getParameter("search_text");
            System.out.println(search_text);
//            创建客户端
            RestHighLevelClient esClient = EsCli.connectES();
            SearchRequest searchRequest = new SearchRequest("blogtext");
            /**
             *  请求方式:termQueryBuilder
             *  关键字查询,keyword类型等全匹配查询  text类型分词后的关键词
             */
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("text_title", "张三");

            /**
             *  查询所有字段,分词检索(使用默认设置的分词器)
             *  如:已设置了ik分词就用该分词器。效果同multi_match "fields": ["*"]
             */
            QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(search_text);

            /**
             *  定义bool查询,适用于多条件组合与过滤查询filter
             */
            BoolQueryBuilder boolQueryBuilder= QueryBuilders.boolQuery();

            /**
             *  过滤查询-不参与分值排名(ES默认先执行filter在执行bool查询)过滤出包含字段的数据再进行检索
             *  1.提高检索性能
             *  2.提高检索速度
             *  3.全文检索时,优先建议使用
             */
            boolQueryBuilder.filter(new ExistsQueryBuilder("text_title"))
                    .filter(new ExistsQueryBuilder("text_content"));

            /**
             *  bool 关键字: ⽤来组合多个条件实现复杂查询
             *  must: 相当于&& 同时成⽴
             *  should: 相当于|| 成⽴⼀个就⾏
             *  must_not: 相当于! 不能满⾜任何⼀个
             */
            boolQueryBuilder.must(queryStringQueryBuilder)
                    .must(queryStringQueryBuilder)
                    .should(termQueryBuilder)
                    .mustNot(termQueryBuilder);

            /**
             *  定义高亮体
             *  1.requireFieldMatch  —false  其他字段根据关键词也高亮。 —true 只高亮检索的字段
             *  2.* 代表全部字体高亮
             *  3.⾃定义⾼亮标签
             */
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.requireFieldMatch(true)
                    .field("*")
                    .preTags("")
                    .postTags("");

            /**
             *  请求体
             */
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            /**
             * 1.分页
             * 2.排序,不参与得分排名
             * 3.包含的字段与排除的字段
             * 4.添加高亮体
             * 5.添加请求方法 bool
             */
            searchSourceBuilder
                    .from(0)
                    .size(10)
                    .sort("text_views", SortOrder.DESC)
                    .fetchSource(new String[]{"*"}, Strings.EMPTY_ARRAY)
                    .highlighter(highlightBuilder)
                    .query(boolQueryBuilder);
            /**
             * 添加请求体
             */
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = null;
            try {
                searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
//        /**
//         *  获取高亮字段
//         */
//        SearchHit[] hits = searchResponse.getHits().getHits();
//        for (SearchHit hit : hits) {
//            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
//            Set<Map.Entry<String, HighlightField>> entrySet = highlightFields.entrySet();
//            for (Map.Entry<String, HighlightField> entry :entrySet) {
//                System.out.println("高亮字段为:" + entry.getKey());
//                System.out.println("高亮结果为:" + entry.getValue().fragments()[0].toString());
//            }
//        }
            esClient.close();

            System.out.println(searchResponse);
            response.setCharacterEncoding("UTF-8");
            JSONObject allData = JSON.parseObject(String.valueOf(searchResponse));
            response.getWriter().println(allData);
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
          }
    }
运行结果及报错内容

01-Sep-2022 10:04:53.526 严重 [http-nio-8080-exec-2] org.apache.catalina.core.StandardWrapperValve.invoke 在路径为/BlogSystem的上下文中,Servlet[com.web.httpservlet.AllHttpServlet]的Servlet.service()引发了具有根本原因的异常Servlet执行抛出一个异常
java.lang.ClassNotFoundException: org.elasticsearch.index.query.QueryBuilder
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1372)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1195)
at com.web.httpservlet.AllHttpServlet.doGet(AllHttpServlet.java:64)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:201)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:364)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1629)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

pom.xml:

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.6.1</version>
        </dependency>
        
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.6.1</version>
        </dependency>
我想要达到的结果

但是我将全文检索的代码封装成函数单独运行时是可以正常运行的。只是放到javaweb里,启动tomcat后发生错误。求告知是什么原因导致的,我该如何解决。

  • 写回答

1条回答 默认 最新

  • 臭小子帅 2022-09-01 11:56
    关注

    把你的pom.xml发个完整的;idea可以看下右边项目的dependency里面的es版本是不是一致的;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 9月9日
  • 已采纳回答 9月1日
  • 创建了问题 9月1日

悬赏问题

  • ¥15 visionmaster启动失败,提示为“机器不满足授权而被禁用”
  • ¥50 用logisim设计16位单时钟周期cpu
  • ¥15 IDEA中圈复杂度如何具体设置
  • ¥50 labview采集不了数据
  • ¥15 请上面代码做什么处理或什么混淆
  • ¥15 英雄联盟自定义房间置顶
  • ¥15 W5500网线插上无反应
  • ¥15 如何用字典的Key,显示在WPF的xaml中
  • ¥15 weautomate读取Excel表格信息然后填写到网页一直报错,如何解决?
  • ¥15 C#如何在Webview2中获取网页验证码