lucene中的高亮

Lucene学习之高亮显示 在搜索引擎中我们经常会看到这样的情景: 红色部分我们称之为高亮显示,lucene提供了HighLighter模块来实现这一功能。 高亮显示模块通常包含两个独立的功能,首先是动态拆分,就是从匹配搜索的大量文本中选取一小部分句子。第二个内容就是高亮显示。 我们先来看下高亮显示的原理: 一、TokenSources:IndexReader reader = DirectoryReader.op 阅读详情

这里我们搜索的内容是“一步一步跟我学习lucene”,搜索引擎展示的结果中对用户的输入信息进行了配色方面的处理,这种区分正常文本和输入内容的效果即是高亮显示;

这样做的好处:

  • 视觉上让人便于查找有搜索对应的文本块;
  • 界面展示更友好;

lucene提供了highlighter插件来体现类似的效果;

highlighter对查询关键字高亮处理;

highlighter包包含了用于处理结果页查询内容高亮显示的功能,其中Highlighter类highlighter包的核心组件,借助Fragmenter, fragment Scorer, 和Formatter等类来支持用户自定义高亮展示的功能;

示例程序

这里边我利用了之前的做的目录文件索引

[java]  view plain  copy
  1. package com.lucene.search.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.StringReader;  
  5. import java.util.concurrent.ExecutorService;  
  6. import java.util.concurrent.Executors;  
  7.   
  8. import org.apache.lucene.analysis.Analyzer;  
  9. import org.apache.lucene.analysis.TokenStream;  
  10. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  11. import org.apache.lucene.document.Document;  
  12. import org.apache.lucene.index.Term;  
  13. import org.apache.lucene.search.IndexSearcher;  
  14. import org.apache.lucene.search.ScoreDoc;  
  15. import org.apache.lucene.search.TermQuery;  
  16. import org.apache.lucene.search.TopDocs;  
  17. import org.apache.lucene.search.highlight.Highlighter;  
  18. import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;  
  19. import org.apache.lucene.search.highlight.QueryScorer;  
  20. import org.apache.lucene.search.highlight.SimpleFragmenter;  
  21. import org.apache.lucene.search.highlight.SimpleHTMLFormatter;  
  22. import org.apache.lucene.util.BytesRef;  
  23.   
  24. public class HighlighterTest {  
  25.       public static void main(String[] args) {  
  26.         IndexSearcher searcher;  
  27.         TopDocs docs;   
  28.         ExecutorService service = Executors.newCachedThreadPool();  
  29.         try {  
  30.             searcher = SearchUtil.getMultiSearcher("index", service);  
  31.             Term term = new Term("content",new BytesRef("lucene"));  
  32.             TermQuery termQuery = new TermQuery(term);  
  33.             docs = SearchUtil.getScoreDocsByPerPage(1, 30, searcher, termQuery);  
  34.             ScoreDoc[] hits = docs.scoreDocs;  
  35.             QueryScorer scorer = new QueryScorer(termQuery);  
  36.             SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<B>","</B>");//设定高亮显示的格式<B>keyword</B>,此为默认的格式    
  37.             Highlighter highlighter = new Highlighter(simpleHtmlFormatter,scorer);     
  38.             highlighter.setTextFragmenter(new SimpleFragmenter(20));//设置每次返回的字符数  
  39.             Analyzer analyzer = new StandardAnalyzer();  
  40.             for(int i=0;i<hits.length;i++){     
  41.                 Document doc = searcher.doc(hits[i].doc);     
  42.                 String str = highlighter.getBestFragment(analyzer, "content", doc.get("content")) ;  
  43.                 System.out.println(str);     
  44.             }     
  45.   
  46.         } catch (IOException e1) {  
  47.             // TODO Auto-generated catch block  
  48.             e1.printStackTrace();  
  49.         } catch (InvalidTokenOffsetsException e) {  
  50.             // TODO Auto-generated catch block  
  51.             e.printStackTrace();  
  52.         }finally{  
  53.             service.shutdown();  
  54.         }  
  55.     }  
  56. }  

lucene的highlighter高亮展示的原理:

  • 根据Formatter和Scorer创建highlighter对象,formatter定义了高亮的显示方式,而scorer定义了高亮的评分;

评分的算法是先根据term的评分值获取对应的document的权重,在此基础上对文本的内容进行轮询,获取对应的文本出现的次数,和它在term对应的文本中出现的位置(便于高亮处理),评分并分词的算法为:

[java]  view plain  copy
  1. public float getTokenScore() {  
  2.     position += posIncAtt.getPositionIncrement();//记录出现的位置  
  3.     String termText = termAtt.toString();  
  4.   
  5.     WeightedSpanTerm weightedSpanTerm;  
  6.   
  7.     if ((weightedSpanTerm = fieldWeightedSpanTerms.get(  
  8.               termText)) == null) {  
  9.       return 0;  
  10.     }  
  11.   
  12.     if (weightedSpanTerm.positionSensitive &&  
  13.           !weightedSpanTerm.checkPosition(position)) {  
  14.       return 0;  
  15.     }  
  16.   
  17.     float score = weightedSpanTerm.getWeight();//获取权重  
  18.   
  19.     // found a query term - is it unique in this doc?  
  20.     if (!foundTerms.contains(termText)) {//结果排重处理  
  21.       totalScore += score;  
  22.       foundTerms.add(termText);  
  23.     }  
  24.   
  25.     return score;  
  26.   }  

formatter的原理为:对搜索的文本进行判断,如果scorer获取的totalScore不小于0,即查询内容在对应的term中存在,则按照格式拼接成preTag+查询内容+postTag的格式

详细算法如下:

[java]  view plain  copy
  1. public String highlightTerm(String originalText, TokenGroup tokenGroup) {  
  2.     if (tokenGroup.getTotalScore() <= 0) {  
  3.       return originalText;  
  4.     }  
  5.   
  6.     // Allocate StringBuilder with the right number of characters from the  
  7.     // beginning, to avoid char[] allocations in the middle of appends.  
  8.     StringBuilder returnBuffer = new StringBuilder(preTag.length() + originalText.length() + postTag.length());  
  9.     returnBuffer.append(preTag);  
  10.     returnBuffer.append(originalText);  
  11.     returnBuffer.append(postTag);  
  12.     return returnBuffer.toString();  
  13.   }  

其默认格式为“<B></B>”的形式;

  • Highlighter根据scorer和formatter,对document进行分析,查询结果调用getBestTextFragments,TokenStream tokenStream,String text,boolean mergeContiguousFragments,int maxNumFragments),其过程为
  1. scorer首先初始化查询内容对应的出现位置的下标,然后对tokenstream添加PositionIncrementAttribute,此类记录单词出现的位置;
  2. 对文本内容进行轮询,判断查询的文本长度是否超出限制,如果超出文本长度提示过长内容;
  3. 如果获取到指定的文本,先对单次查询的内容进行内容的截取(截取值根据setTextFragmenter指定的值决定),再调用formatter的highlightTerm方法对文本进行重新构建
  4. 在本次轮询和下次单词出现之前对文本内容进行处理

查询工具类

[java]  view plain  copy
  1. package com.lucene.search.util;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.nio.file.Paths;  
  6. import java.util.Set;  
  7. import java.util.concurrent.ExecutorService;  
  8.   
  9. import org.apache.lucene.analysis.Analyzer;  
  10. import org.apache.lucene.analysis.standard.StandardAnalyzer;  
  11. import org.apache.lucene.document.Document;  
  12. import org.apache.lucene.index.DirectoryReader;  
  13. import org.apache.lucene.index.IndexReader;  
  14. import org.apache.lucene.index.MultiReader;  
  15. import org.apache.lucene.index.Term;  
  16. import org.apache.lucene.queryparser.classic.ParseException;  
  17. import org.apache.lucene.queryparser.classic.QueryParser;  
  18. import org.apache.lucene.search.BooleanQuery;  
  19. import org.apache.lucene.search.IndexSearcher;  
  20. import org.apache.lucene.search.MatchAllDocsQuery;  
  21. import org.apache.lucene.search.NumericRangeQuery;  
  22. import org.apache.lucene.search.Query;  
  23. import org.apache.lucene.search.ScoreDoc;  
  24. import org.apache.lucene.search.TermQuery;  
  25. import org.apache.lucene.search.TopDocs;  
  26. import org.apache.lucene.search.BooleanClause.Occur;  
  27. import org.apache.lucene.search.highlight.Highlighter;  
  28. import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;  
  29. import org.apache.lucene.search.highlight.QueryScorer;  
  30. import org.apache.lucene.search.highlight.SimpleFragmenter;  
  31. import org.apache.lucene.search.highlight.SimpleHTMLFormatter;  
  32. import org.apache.lucene.store.FSDirectory;  
  33. import org.apache.lucene.util.BytesRef;  
  34.   
  35. /**lucene索引查询工具类 
  36.  * @author lenovo 
  37.  * 
  38.  */  
  39. public class SearchUtil {  
  40.     /**获取IndexSearcher对象 
  41.      * @param indexPath 
  42.      * @param service 
  43.      * @return 
  44.      * @throws IOException 
  45.      */  
  46.     public static IndexSearcher getIndexSearcherByParentPath(String parentPath,ExecutorService service) throws IOException{  
  47.         MultiReader reader = null;  
  48.         //设置  
  49.         try {  
  50.             File[] files = new File(parentPath).listFiles();  
  51.             IndexReader[] readers = new IndexReader[files.length];  
  52.             for (int i = 0 ; i < files.length ; i ++) {  
  53.                 readers[i] = DirectoryReader.open(FSDirectory.open(Paths.get(files[i].getPath(), new String[0])));  
  54.             }  
  55.             reader = new MultiReader(readers);  
  56.         } catch (IOException e) {  
  57.             // TODO Auto-generated catch block  
  58.             e.printStackTrace();  
  59.         }  
  60.         return new IndexSearcher(reader,service);  
  61.     }  
  62.     /**多目录多线程查询 
  63.      * @param parentPath 父级索引目录 
  64.      * @param service 多线程查询 
  65.      * @return 
  66.      * @throws IOException 
  67.      */  
  68.     public static IndexSearcher getMultiSearcher(String parentPath,ExecutorService service) throws IOException{  
  69.         File file = new File(parentPath);  
  70.         File[] files = file.listFiles();  
  71.         IndexReader[] readers = new IndexReader[files.length];  
  72.         for (int i = 0 ; i < files.length ; i ++) {  
  73.             readers[i] = DirectoryReader.open(FSDirectory.open(Paths.get(files[i].getPath(), new String[0])));  
  74.         }  
  75.         MultiReader multiReader = new MultiReader(readers);  
  76.         IndexSearcher searcher = new IndexSearcher(multiReader,service);  
  77.         return searcher;  
  78.     }  
  79.     /**根据索引路径获取IndexReader 
  80.      * @param indexPath 
  81.      * @return 
  82.      * @throws IOException 
  83.      */  
  84.     public static DirectoryReader getIndexReader(String indexPath) throws IOException{  
  85.         return DirectoryReader.open(FSDirectory.open(Paths.get(indexPath, new String[0])));  
  86.     }  
  87.     /**根据索引路径获取IndexSearcher 
  88.      * @param indexPath 
  89.      * @param service 
  90.      * @return 
  91.      * @throws IOException 
  92.      */  
  93.     public static IndexSearcher getIndexSearcherByIndexPath(String indexPath,ExecutorService service) throws IOException{  
  94.         IndexReader reader = getIndexReader(indexPath);  
  95.         return new IndexSearcher(reader,service);  
  96.     }  
  97.       
  98.     /**如果索引目录会有变更用此方法获取新的IndexSearcher这种方式会占用较少的资源 
  99.      * @param oldSearcher 
  100.      * @param service 
  101.      * @return 
  102.      * @throws IOException 
  103.      */  
  104.     public static IndexSearcher getIndexSearcherOpenIfChanged(IndexSearcher oldSearcher,ExecutorService service) throws IOException{  
  105.         DirectoryReader reader = (DirectoryReader) oldSearcher.getIndexReader();  
  106.         DirectoryReader newReader = DirectoryReader.openIfChanged(reader);  
  107.         return new IndexSearcher(newReader, service);  
  108.     }  
  109.       
  110.     /**多条件查询类似于sql in 
  111.      * @param querys 
  112.      * @return 
  113.      */  
  114.     public static Query getMultiQueryLikeSqlIn(Query ... querys){  
  115.         BooleanQuery query = new BooleanQuery();  
  116.         for (Query subQuery : querys) {  
  117.             query.add(subQuery,Occur.SHOULD);  
  118.         }  
  119.         return query;  
  120.     }  
  121.       
  122.     /**多条件查询类似于sql and 
  123.      * @param querys 
  124.      * @return 
  125.      */  
  126.     public static Query getMultiQueryLikeSqlAnd(Query ... querys){  
  127.         BooleanQuery query = new BooleanQuery();  
  128.         for (Query subQuery : querys) {  
  129.             query.add(subQuery,Occur.MUST);  
  130.         }  
  131.         return query;  
  132.     }  
  133.     /**从指定配置项中查询 
  134.      * @return 
  135.      * @param analyzer 分词器 
  136.      * @param field 字段 
  137.      * @param fieldType 字段类型 
  138.      * @param queryStr 查询条件 
  139.      * @param range 是否区间查询 
  140.      * @return 
  141.      */  
  142.     public static Query getQuery(String field,String fieldType,String queryStr,boolean range){  
  143.         Query q = null;  
  144.         try {  
  145.             if(queryStr != null && !"".equals(queryStr)){  
  146.                 if(range){  
  147.                     String[] strs = queryStr.split("\\|");  
  148.                     if("int".equals(fieldType)){  
  149.                         int min = new Integer(strs[0]);  
  150.                         int max = new Integer(strs[1]);  
  151.                         q = NumericRangeQuery.newIntRange(field, min, max, true, true);  
  152.                     }else if("double".equals(fieldType)){  
  153.                         Double min = new Double(strs[0]);  
  154.                         Double max = new Double(strs[1]);  
  155.                         q = NumericRangeQuery.newDoubleRange(field, min, max, true, true);  
  156.                     }else if("float".equals(fieldType)){  
  157.                         Float min = new Float(strs[0]);  
  158.                         Float max = new Float(strs[1]);  
  159.                         q = NumericRangeQuery.newFloatRange(field, min, max, true, true);  
  160.                     }else if("long".equals(fieldType)){  
  161.                         Long min = new Long(strs[0]);  
  162.                         Long max = new Long(strs[1]);  
  163.                         q = NumericRangeQuery.newLongRange(field, min, max, true, true);  
  164.                     }  
  165.                 }else{  
  166.                     if("int".equals(fieldType)){  
  167.                         q = NumericRangeQuery.newIntRange(field, new Integer(queryStr), new Integer(queryStr), true, true);  
  168.                     }else if("double".equals(fieldType)){  
  169.                         q = NumericRangeQuery.newDoubleRange(field, new Double(queryStr), new Double(queryStr), true, true);  
  170.                     }else if("float".equals(fieldType)){  
  171.                         q = NumericRangeQuery.newFloatRange(field, new Float(queryStr), new Float(queryStr), true, true);  
  172.                     }else{  
  173.                         Analyzer analyzer = new StandardAnalyzer();  
  174.                         q = new QueryParser(field, analyzer).parse(queryStr);  
  175.                     }  
  176.                 }  
  177.             }else{  
  178.                 q= new MatchAllDocsQuery();  
  179.             }  
  180.               
  181.             System.out.println(q);  
  182.         } catch (ParseException e) {  
  183.             // TODO Auto-generated catch block  
  184.             e.printStackTrace();  
  185.         }  
  186.         return q;  
  187.     }  
  188.     /**根据field和值获取对应的内容 
  189.      * @param fieldName 
  190.      * @param fieldValue 
  191.      * @return 
  192.      */  
  193.     public static Query getQuery(String fieldName,Object fieldValue){  
  194.         Term term = new Term(fieldName, new BytesRef(fieldValue.toString()));  
  195.         return new TermQuery(term);  
  196.     }  
  197.     /**根据IndexSearcher和docID获取默认的document 
  198.      * @param searcher 
  199.      * @param docID 
  200.      * @return 
  201.      * @throws IOException 
  202.      */  
  203.     public static Document getDefaultFullDocument(IndexSearcher searcher,int docID) throws IOException{  
  204.         return searcher.doc(docID);  
  205.     }  
  206.     /**根据IndexSearcher和docID 
  207.      * @param searcher 
  208.      * @param docID 
  209.      * @param listField 
  210.      * @return 
  211.      * @throws IOException 
  212.      */  
  213.     public static Document getDocumentByListField(IndexSearcher searcher,int docID,Set<String> listField) throws IOException{  
  214.         return searcher.doc(docID, listField);  
  215.     }  
  216.       
  217.     /**分页查询 
  218.      * @param page 当前页数 
  219.      * @param perPage 每页显示条数 
  220.      * @param searcher searcher查询器 
  221.      * @param query 查询条件 
  222.      * @return 
  223.      * @throws IOException 
  224.      */  
  225.     public static TopDocs getScoreDocsByPerPage(int page,int perPage,IndexSearcher searcher,Query query) throws IOException{  
  226.         TopDocs result = null;  
  227.         if(query == null){  
  228.             System.out.println(" Query is null return null ");  
  229.             return null;  
  230.         }  
  231.         ScoreDoc before = null;  
  232.         if(page != 1){  
  233.             TopDocs docsBefore = searcher.search(query, (page-1)*perPage);  
  234.             ScoreDoc[] scoreDocs = docsBefore.scoreDocs;  
  235.             if(scoreDocs.length > 0){  
  236.                 before = scoreDocs[scoreDocs.length - 1];  
  237.             }  
  238.         }  
  239.         result = searcher.searchAfter(before, query, perPage);  
  240.         return result;  
  241.     }  
  242.     public static TopDocs getScoreDocs(IndexSearcher searcher,Query query) throws IOException{  
  243.         TopDocs docs = searcher.search(query, getMaxDocId(searcher));  
  244.         return docs;  
  245.     }  
  246.     /**高亮显示字段 
  247.      * @param searcher 
  248.      * @param field 
  249.      * @param keyword 
  250.      * @param preTag 
  251.      * @param postTag 
  252.      * @param fragmentSize 
  253.      * @return 
  254.      * @throws IOException  
  255.      * @throws InvalidTokenOffsetsException  
  256.      */  
  257.     public static String[] highlighter(IndexSearcher searcher,String field,String keyword,String preTag, String postTag,int fragmentSize) throws IOException, InvalidTokenOffsetsException{  
  258.         Term term = new Term("content",new BytesRef("lucene"));  
  259.         TermQuery termQuery = new TermQuery(term);  
  260.         TopDocs docs = getScoreDocs(searcher, termQuery);  
  261.         ScoreDoc[] hits = docs.scoreDocs;  
  262.         QueryScorer scorer = new QueryScorer(termQuery);  
  263.         SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter(preTag,postTag);//设定高亮显示的格式<B>keyword</B>,此为默认的格式    
  264.         Highlighter highlighter = new Highlighter(simpleHtmlFormatter,scorer);     
  265.         highlighter.setTextFragmenter(new SimpleFragmenter(fragmentSize));//设置每次返回的字符数  
  266.         Analyzer analyzer = new StandardAnalyzer();  
  267.         String[] result = new String[hits.length];  
  268.         for (int i = 0; i < result.length ; i++) {  
  269.             Document doc = searcher.doc(hits[i].doc);  
  270.             result[i] = highlighter.getBestFragment(analyzer, field, doc.get(field));  
  271.         }  
  272.         return result;  
  273.     }  
  274.     /**统计document的数量,此方法等同于matchAllDocsQuery查询 
  275.      * @param searcher 
  276.      * @return 
  277.      */  
  278.     public static int getMaxDocId(IndexSearcher searcher){  
  279.         return searcher.getIndexReader().maxDoc();  
  280.     }  
  281.       
  282. }  
Lucene的高级使用之高亮显示 1.1、高亮显示 原理: 1)给所有关键字加上一个HTML标签 2)给这个特殊的标签设置CSS样式 代码实现: // 高亮显示 @Test public void testHighlighter() throws Exception { // 目录对象 Directory directory = FSDirectory.open(... 阅读详情

相关推荐

【lucene】高亮案例

只要 字段存储原文并开启 Term Vector,Lucene 8.5 用 Highlighter + QueryScorer 即可轻松实现关键字高亮,无需 ES 也能获得 `<font>` 或 `<span>` 标签效果。高亮器 `Highlighter`(普通文本) / `FastVectorHighlighter`(性能更好,但需额外配置)/* ---------- 2. 搜索 + 高亮 ---------- *//* ---------- 1. 建索引 ---------- */

risc123456的博客 930

Lucene的全文搜索及高亮显示

【代码】Lucene的全文搜索及高亮显示。

天真吖的博客 978

【lucene】lucene高亮显示

1.概述 public final void lighter01() { try { String txt = "我爱北京天安门,伟大的毛主席"; Query query = new QueryParser(Version.LUCENE_35, "f", new MMSegAnalyzer()).parse("伟大"); QueryScorer scorer = new QueryScorer(query); Fragmenter fragment = new SimpleSp

九师兄 343

Lucene高亮显示详解

在Lucene的org.apache.lucene.search.highlight包中提供了关于高亮显示检索关键字的工具。使用百度、 Google搜索的时候,检索结果显示的时候,在摘要中实现与关键字相同的词条进行高亮显示,百度和Google指定红色高亮显示。 有了Lucene提供的高亮显示的工具,可以很方便地实现高亮显示的功能。 高亮显示,就是根据用户输入的检索关键字,检索找到该

jazywoo_在路上 1560

IKAnalyzer LUCENE.4.9 中文分词的高亮显示

利用IKAnalyzer结合LUCENE.4.9进行中文分词的高亮显示。

lucene第一步---5.中文分词IKAnalyzer和高亮highlighter的使用

NULL 博文链接:https://llying.iteye.com/blog/570208

lucene高亮

/*      * lucene 高亮      */     @Test     public void highLighter(){         try {             String queryString = "钢铁侠";             Analyzer analyzer = new IKAnalyzer();             QueryPa

783

Halcon 20.11在WPF中的交互式绘图:完整实现矩形ROI的创建、拖动与坐标获取

本文详细介绍了如何在WPF框架下利用Halcon 20.11实现交互式矩形ROI的创建、拖动与坐标获取。通过HDrawingObject和HSmartWindowControlWPF控件,开发者可以高效构建机器视觉应用,提升项目实战中的开发效率。文章涵盖环境配置、事件处理、坐标获取及性能优化等关键内容。

weixin_29266007的博客 427

lucene高亮显示

Lucene针对高亮显示功能提供了两种实现方式,分别是Highlighter和FastVectorHighlighter 顾名思义,FastVectorHighlighter较Highlighter速度更快,功能也更强大,但是有使用前提:创建索引时,需要存储Field的分词向量信息(TermVector.WITH_POSITIONS_OFFSETS),而Highlighter则不需要,如何在时间

JavaMan_chen的专栏 8957

UUVsimulator仿真

pub -r 10 /cmd_vel geometry_msgs/Twist控制运动没有反应。通过键盘控制运动,接收不到/cmd_vel消息。

Fatal__的博客 4607

从TL431光耦到集成隔离器:3种反激电源反馈方案全对比,你的项目到底该选哪个?

本文深入对比了反激电源设计中TL431光耦、集成隔离器和原边反馈三种主流反馈方案的优缺点,帮助开发者在电源设计中选择最适合的方案。从精度、成本、隔离等级等多维度分析,为反激式(Flyback)拓扑的应用提供实用选型指南。

weixin_30536513的博客 399

lucene 高亮 文件

对于 的字段来说,因为stored=false,所以没有默认高亮方式。    我们可以自己获取文本(如数据库中的clob字段,pdf文件中的内容),然后再调用lucene的相关api实现。    import java.io.IOException; import java.io.StringReader; import org.apache.lucene.analysis.Token

shizhan1881的专栏 936

YOLO11改进 | 卷积模块 | 轻量化GSConv替换普通的conv

yolo11,GSConv,卷积模块

kay_545 3958

Lucene高亮显示

前面一节我们基本了解了Lucene的一些基本使用,索引的创建,搜索。 接下去让我们的搜索结果高亮! 需要的架包(版本比较低~) org.apache.lucene lucene-core 2.3.0 org.apache.lucene lucene-highlighter 2.3.0

TangXW的博客 466

RAG系统中Embedding模型选型实战

本文详细介绍了RAG系统中Embedding模型选型实战,希望能对学习RAG的同学们有所帮助。 文章目录 1. 前言 2. 思路解析 3. 测评数据集构建 3.1 步骤一 3.2 步骤二 3.3 数据示例 3.4 总结 4. 实战代码 4.1 本地模型 4.2 使用第三方的Embedding模型API

herosunly的博客 17万+

【kafka】控制台默认不能发送大数据 4096 4095 4129

1.概述 因为某些原因,需要做一个测试,然后我想往topic中,发送一条消息,然后再消费它。但是消息有点大,一条消息是36K. 消费者 [root@1 kafka]# bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic xxx.devicealarm | grep 网络攻击 生产者,生产者发送了一个消息消息是一个json,json中有这个数据特征 网络攻击 [root@1 kafka]# bin/kafka-console-p

九师兄 587

Lucene的高亮

1.加入高亮的架包<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/ma

jsaber的博客 525

《YOLOv8:从入门到实战》专栏介绍 & 专栏目录

本专栏涵盖了丰富的YOLOv8算法从入门到实战系列教程,专为学习YOLOv8的同学而设计,堪称全网最详细的教程!🌈🌈🌈

小哥谈 6491

Lucene关键字高亮显示

  在Lucene的org.apache.lucene.search.highlight包中提供了关于高亮显示检索关键字的工具。使用百度、Google搜索的时候,检索结果显示的时候,在摘要中实现与关键字相同的词条进行高亮显示,百度和Google指定红色高亮显示。有了Lucene提供的高亮显示的工具,可以很方便地实现高亮显示的功能。高亮显示,就是根据用户输入的检索关键字

gunner086的专栏 5300

第二十一:Python接口自动化-处理Json数据

【代码】第二十一:Python接口自动化-处理Json数据。

欢迎来到本博客! 111

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Lucene查询结果高亮

检索结果高亮对于用户的体验度和友好度非常重要,可以快速标记出用户检索对关键词。本例中的索引仍使用上一篇博客( Lucene查询索引)中创建的索引,代码高亮参考了Lucene4.x高亮 fast高亮 前端高亮。实现效果:核心代码package ucas.ir.lucene;import java.io.File; import java.io.IOException;import javax.prin

1.02^365=1377.41 5387

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Lucene4.x高亮 fast高亮 前端高亮

原地址:http://qindongliang1922.iteye.com/blog/1953409 高亮功能一直都是全文检索的一项非常优秀的模块,在一个标准的搜索引擎中,高亮的返回命中结果,几乎是必不可少的一项需求,因为通过高亮,我们可以在我们的搜索界面上快速标记出用户的检索关键词,从而减少了用户自己寻找想要的结果,在一定程度上大大提高了用户的体验性和友好度。 那么,散仙今天就来

七夜之家 3162

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Lucene-排序+高亮

public class SortTest { /** * 1、相同的结构,相同的关键词,得分一样 * 2、相同的结构,不同的关键词,得分不一样,一般来说中文比较高 * 3、不同的结构,关键词出现的次数越多,得分越高 * 4、利用document.setBoost(100)可以人为的提高相关度得分 * @throws Exception */ @Test public

球球之家 718

Lucene 高亮功能

原文转载自: http://qindongliang1922.iteye.com/blog/1953409  高亮功能一直都是全文检索的一项非常优秀的模块,在一个标准的搜索引擎中,高亮的返回命中结果,几乎是必不可少的一项需求,因为通过高亮,我们可以在我们的搜索界面上快速标记出用户的检索关键词,从而减少了用户自己寻找想要的结果,在一定程度上大大提高了用户的体验性和友好度。  那

安源 413
上一篇: Lucene使用案例
下一篇: Json解析
Java_funds
博客等级 码龄9年 6粉丝 22原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值