Home > database >  type mismatch error : cannot convert from List<Hit<feed>> to List<Hit>
type mismatch error : cannot convert from List<Hit<feed>> to List<Hit>

Time:01-02

i am getting this error Type mismatch: cannot convert from List<Hit> to List in my springboot (v2.7.2) application with elasticsearch 7.17.3

Ui Controller

@GetMapping("/searchDoc")
    public String searchDoc(@RequestParam(name = "id", required=false) String id  , Model model ) throws IOException
    {
        model.addAttribute("listfeedDocuments",elasticSearchQuery.search(id));
   
        return "home";
    }

Elasticsearchquerry class

 public  List<feed> search(String text) throws IOException {
       
           Query bodyTermQuery = TermQuery.of(tq -> tq.field("body").value(text))._toQuery();
           Query titleTermQuery = TermQuery.of(tq -> tq.field("title").value(text))._toQuery();

           Query matchQuery = MatchQuery.of(mq -> mq.field("comment.c_text").query(text))._toQuery();

           Query nestedQuery = NestedQuery.of(nq -> nq.path("comment").query(matchQuery)
                           .innerHits(ih -> ih.highlight(h -> h.requireFieldMatch(true))))._toQuery();

           SearchResponse<feed> searchResponse = elasticsearchClient.search(
                           s -> s.index("feeds").query(q -> q.bool(b -> b.should(nestedQuery, titleTermQuery, bodyTermQuery))),
                           feed.class);
           List<Hit> hits = searchResponse.hits().hits();
           List<feed> feeds = new ArrayList<>();
           feed f=null;
           for(Hit object : hits){
               f = (feed) object.source();
               System.out.println("Feed : "  f.getComment().get(1).getC_text());
               feeds.add(f); }
           
           return feeds;    
           }

Html Page using thymeleaf

<div   action="#" th:action="@{/searchDoc}" method="get" >
  <input type="text" 
   th:name="id" placeholder="Search" name="id" aria-label="Recipient's username" aria-describedby="basic-addon2">

  <button th:href="@{/searchDoc}" type="submit" >Search</button>
</div>

CodePudding user response:

The error message "Type mismatch: cannot convert from List to List" means that you are trying to assign a value of a specific type (List) to a variable of a more general type (List).

In the search() method of your Elasticsearchquerry class, the hits variable is a List, but you are trying to assign it to a List variable called feeds. To fix this error, you can change the type of the feeds variable to List:

List<Hit> feeds = new ArrayList<>();

Alternatively, you can change the type of the hits variable to List and then cast each Hit object to a feed object before adding it to the list:

List<feed> feeds = new ArrayList<>();
for(Hit object : hits){
    feeds.add((feed) object.source());
}

I hope this helps resolve the error in your code.

  • Related