威尼斯人线上娱乐

实时搜索,List集合去重使用lambda表明式

1 4月 , 2019  

name age sex
Lucy 22 woman
Lily 23 woman
Tom 24 man
Lucy 22 woman
Lily 23 woman
LiLei 25 man

一路talk C栗子吧(第81陆回:C语言实例–使用共享内部存款和储蓄器举办进度间通讯二)


各位看官们,我们好,上三回中我们说的是运用共享内部存款和储蓄器进行进程间通讯的例证,那二次大家接着上贰遍内容继续说采纳共享内部存款和储蓄器进行进度间通讯。闲话休提,言归正转。让我们一道talk
C栗子吧!

我们在上1遍中介绍了共享内部存款和储蓄器的定义和连锁函数的用法,那2遍中大家由此具体的例证来注解什么接纳共享内部存款和储蓄器举行进度间的通讯。上面是运用共享内部存款和储蓄器的具体步骤:

1.概念三个布局体类型,用来作为共享内部存款和储蓄器的品类;
2.利用shmget函数到手共享内部存款和储蓄器,代码中的键使用了111以此自由数字;
3.使用shmat函数把共享连接到进度的地址空间中;
4.从共享内部存款和储蓄器中读取数据,或然向共享内部存款和储蓄器中写入数据;
5.使用shmdt函数把共享内部存款和储蓄器从进度的地方空间中分离出来;
6.使用shmctl函数删除共享内部存储器,需求利用的通令:IPC_RMID;

看官们,正文中就不写代码了,详细的代码放到了自家的财富中,大家能够点击那里下载使用。

下边是程序的周转结果,请我们参考:

./s -r                                  //运行程序并且使用-r参数,表示启动读取数据的进程
there is not any data in share memory   //这时共享内存中还没有数据
./s -w                                  //运行程序并且使用-w参数,表示启动写入数据的进程
write data into share memory.count:3,data:hello share memory //提示写入的数据
./s -r                                //再次运行程序并且使用-r参数,表示启动读取数据的进程                
the data of share memory.count:3,data:hello share memory  //显示从共享内存中读取的数据

在先后中我们采用参数来区分分裂的长河,同时选拔四个标记位来判定共享内部存款和储蓄器中是或不是有数据。其余,使用共享内部存款和储蓄器进行进度间通讯时索要运用同步机制,比如大家在刚开头运营程序时,因为还不曾执行写进度,共享内部存款和储蓄器中没有数据,那时候,读进度不能够从共享内部存储器中读取到数量。

实时搜索,List集合去重使用lambda表明式。各位看官,关于选用共享内部存款和储蓄器进行进程间通讯的例证大家就说到此地。欲知后面还有哪些例子,且听下回分解


 

C栗子吧(第7十八回:C语言实例–使用共享内部存款和储蓄器进行进程间通讯二)
各位看官们,大家好,上贰遍中大家说的是选用共享内部存储器举行…

① 、是还是不是实行实时搜索

  • 实时搜索:只要数据库一变动,马上要翻新索引,要选拔writer.commit来操作,然则那种境况太花费能源。
  • 近实时寻找:当用户修改了音讯之后,先把索引保存到内存中,然后在三个联合的年华内对内部存储器中的目录进行提交操作。基于这一个缘故我们一般实行的是近实时搜索。

截图

screenshot.png

List<Person> list_persons = new List<Person>(new Person("Lucy",22,"woman"),new Person("Lily",23,"woman"),new Person("Tom",24,"man"),new Person("Lucy",22,"woman"),new Person("Lily",23,"woman"),new Person("LiLei",25,"man"));

② 、入门程序(工程lucene-nearRealTime

IndexUtil.java

package cn.itcast.util;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.StaleReaderException;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.search.SearcherWarmer;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

public class IndexUtil {
    private String[] ids = {"1", "2", "3", "4", "5", "6"};
    //下面是邮件
    private String[] emails = {"aa@qq.com", "bb@sina.edu", "cc@yahu.org", "ss@sina.com", "dd@gmail.com", "ee@163.com"};
    //下面是邮件内容
    private String[] content = {
            "welcom to visited the space,I like football", 
            "hello boy, i like someone", 
            "come on baby", 
            "first blood", 
            "I like football,I like football", 
            "my girlfriend is so beatiful, every body like game"
    };
    private int[] attaches = {2,5,6,5,8,4};//附件数量
    //发件人名字
    private String[] names = {"Tom", "Jack", "goudan", "alibaba", "jerry", "kitty"};
    //邮件的日期
    private Date[] dates = null;

    private Directory directory = null;
    private Map<String, Float> scores = new HashMap<String, Float>();//新建一个Map,用来存储权值
    /*private static IndexReader reader = null;//声明一个IndexReader的属性*/
    private SearcherManager mgr = null;

    public IndexUtil() {
        try {
            setDates();//设置日期
            scores.put("qq.com", 2.0f);//如果是"qq.com"结尾的索引则让其权值为2.0,注意:默认是1.0
            scores.put("sina.edu", 1.5f);
            directory = FSDirectory.open(new File("E:/myeclipse/Lucene/index"));
            mgr = new SearcherManager(directory, new SearcherWarmer() {
                //在重新打开的时候可能需要做一个控制,这些控制可以在这个方法中做
                @Override
                public void warm(IndexSearcher searcher) throws IOException {
                    System.out.println("has changed");
                }
            }, Executors.newCachedThreadPool());
        } catch (IOException e) {
            e.printStackTrace(); 
        }
    }

    //创建索引
    public void index(){
        IndexWriter writer = null;
        try {
            writer = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35)));
            //此方法可将索引全部清空
            writer.deleteAll();
            Document document = null;
            for(int i = 0; i < ids.length; i++){
                document = new Document();
                //id需要存储,不需要加权、分词,email也需要存储,但不需要分词,有时候也需要加权
                //对于内容,我们不需要存储和加权,但需要分词。而名字需要存储,不需要分词和加权
                //这里我们先不对整型数据进行索引,后面再说
                document.add(new Field("id", ids[i], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
                document.add(new Field("email", emails[i], Field.Store.YES, Field.Index.NOT_ANALYZED));
                document.add(new Field("content", content[i], Field.Store.NO, Field.Index.ANALYZED));
                document.add(new Field("name", names[i], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));

                //为数字添加索引,第三个参数设置为true表示默认索引
                document.add(new NumericField("attach", Field.Store.YES, true).setIntValue(attaches[i]));
                //为日期添加索引
                document.add(new NumericField("date", Field.Store.YES, true).setLongValue(dates[i].getTime()));


                String et = emails[i].substring(emails[i].lastIndexOf("@") + 1);
                System.out.println(et);
                //加入权值
                if(scores.containsKey(et)){
                    document.setBoost(scores.get(et));
                }else{
                    document.setBoost(0.5f);
                }
                writer.addDocument(document);
            }
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (LockObtainFailedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(writer != null){
                try {
                    writer.close();
                } catch (CorruptIndexException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //查询
    public void query(){
        try {
            IndexReader reader = IndexReader.open(directory);
            //maxDoc 和 numDocs()方法的区别:maxDoc()返回索引中删除和未被删除的文档总数,
            //后者返回索引中未被删除的文档总数,通过reader可以有效获取文档的数量
            System.out.println("numDocs: " + reader.numDocs());
            System.out.println("maxDocs: " + reader.maxDoc());
            //查看被删除的索引
            System.out.println("deleteDocs : " + reader.numDeletedDocs());
            //记得用完之后关闭
            reader.close();

        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //删除索引
    public void delete(){
        IndexWriter writer = null;
        try {
            writer = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35)));

            //参数可以是一个选项,可以是一个query,也可以是一个term,term是一个精确查找的值
            //这里我们测试此方法之后再次执行搜索方法,发现文档数numDocs还有5个,比之前少了一个,但是maxDoc还是6个
            //在我们的索引目录中发现出现了一个delete的文件。这里的删除就像一个回收站一样,是可以恢复的
            writer.deleteDocuments(new Term("id", "1"));//这里表示删除索引为1的id
            writer.commit();
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (LockObtainFailedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //更新索引
    public void update(){
        IndexWriter writer = null;
        try {
            writer = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35)));

            /* lucene并没有提供更新,这里的更新操作其实是如下两个操作的合集
             * 先删除之后再添加,所以不是在之前的位置更新
             * 测试之后我们会发现回收站中有一个索引
             * */
            Document document = new Document();
            document.add(new Field("id", "11", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
            document.add(new Field("email", emails[0], Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.add(new Field("content", content[0], Field.Store.NO, Field.Index.ANALYZED));
            document.add(new Field("name", names[0], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
            writer.updateDocument(new Term("id", "1"), document);
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (LockObtainFailedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(writer != null){
                try {
                    writer.close();
                } catch (CorruptIndexException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void search01(){
        IndexReader reader;
        try {
            reader = IndexReader.open(directory);
            IndexSearcher searcher = new IndexSearcher(reader);
            TermQuery query = new TermQuery(new Term("content", "like"));//搜索内容中含有like的
            TopDocs tds = searcher.search(query, 10);
            for(ScoreDoc sd : tds.scoreDocs){
                Document doc = searcher.doc(sd.doc);
                //这里我们获取权值getBoost()的时候发现都是1.0,这是因为这里是获取的一个document,和原来的没有关系。
                //要想看其权值信息,可以使用luke工具
                //而这里的日期需要我们转换成日期格式
                System.out.println("(" + sd.doc + "权值:"+ doc.getBoost() + ")" + doc.get("name") + "[" + doc.get("email") + "]-->" 
                            + doc.get("id") + "-->" + doc.get("attach") + "-->" + doc.get("date"));
                reader.close();
            }
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //设置日期
    private void setDates(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dates = new Date[ids.length];
            dates[0] = sdf.parse("2015-02-15");
            dates[1] = sdf.parse("2015-03-01");
            dates[2] = sdf.parse("2015-05-18");
            dates[3] = sdf.parse("2015-09-05");
            dates[4] = sdf.parse("2015-12-15");
            dates[5] = sdf.parse("2015-08-29");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    public void search02(){
        IndexSearcher searcher = null;
        try {
            mgr.maybeReopen();//判断是否需要重新打开一个IndexSearcher
            searcher = mgr.acquire();
            TermQuery query = new TermQuery(new Term("content", "like"));//搜索内容中含有like的
            TopDocs tds = searcher.search(query, 10);
            for(ScoreDoc sd : tds.scoreDocs){
                Document doc = searcher.doc(sd.doc);
                System.out.println("(" + sd.doc + "权值:"+ doc.getBoost() + ")" + doc.get("name") + "[" + doc.get("email") + "]-->" 
                            + doc.get("id") + "-->" + doc.get("attach") + "-->" + doc.get("date"));
            }
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                mgr.release(searcher);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

说明:那是大家前边写过的贰个工具类,和事先分歧的是大家那边不再直接得到IndexReader,而是定义2个SearcherManager对象:

private SearcherManager mgr = null;

然后对IndexUtil形式开始展览改造,大家经过SearcherManager来管理IndexReader,同时在大家立异索引的长河中大家还足以对能源做一些操作。再对章程search02方法举行改建,这里大家是通过SearcherManager来获得IndexReader对象的,同时是还是不是打开1个新的IndexReaderSearcherManager的方法maybeReopen来控制。而利用完事后我们也不需求关闭IndexReader,只须求将其获释即可,使用情势release

上边举办测试:

package cn.lucene.test;
import org.junit.Test;
import cn.itcast.util.IndexUtil;

public class TestIndex {
    @Test
    public void testIndex(){
        IndexUtil util = new IndexUtil();
        util.index();
    }

    @Test
    public void testQuery(){
        IndexUtil util = new IndexUtil();
        util.query();
    }

    @Test
    public void testDelete(){
        IndexUtil util = new IndexUtil();
        util.delete();
    }

    @Test
    public void testUpdate(){
        IndexUtil util = new IndexUtil();
        util.update();
    }
    @Test
    public void testSearch01(){
        IndexUtil util = new IndexUtil();
        util.search01();
    }
    @Test
    public void testSearch02(){
        IndexUtil util = new IndexUtil();
        for(int i = 0; i < 5; i++){
            util.search02();//这里我们让其执行5次
            System.out.println("************************");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

说明:在测试方法testSearch02此前大家先利用办法testIndex重建索引,然后大家选取方法testQuery能够见见记录数:

威尼斯人线上娱乐 1

1

而在testSearch02办法还平昔不运营完时大家应用testDelete措施开始展览删减,此时我们发现testSearch02方法在后头的出口少了一条记下。将记录0给删除了。即便如此,当大家重新行使testQuery格局查询的时候发现记录没有被删掉,那是因为并没有付诸,而选用SearcherManager要求展开writer.commit才会检查和测试到,于是那就须求动用NRTManager那些类了。

注意:我们在reopen时可能必要对有个别财富做一些操作,能够在措施SearcherWarmer. Warm中进行,我们在testSearch02格局的出口中也足以看出打字与印刷出了has changed

安装

(你须求2个有Python扶助的Vim版本. 请使用 vim --version | grep +python
来检查)

  • 依赖(Debian/Ubuntu 平台)

    sudo apt-get install python vim exuberant-ctags git

    sudo pip install dbgp vim-debug pep8 flake8 pyflakes isort

  • 依赖(RedHat/CentOS 平台)

    CentOS 6.7的yum源自带的Python版本较旧,推荐活动设置Python2.7.

    sudo yum install python vim ctags git

    sudo pip install dbgp vim-debug pep8 flake8 pyflakes isort

  • 依赖(Mac OS 平台)

    brew install python vim git

    wget http://tenet.dl.sourceforge.net/project/ctags/ctags/5.8/ctags-5.8.tar.gz && tar -zxvf ctags-5.8.tar.gz && cd ctags-5.8 && ./configure && make && sudo make install

    sudo pip install dbgp vim-debug pep8 flake8 pyflakes isort

  • 下载vimrc 文件到用户主目录

    wget https://raw.githubusercontent.com/tao12345666333/vim/master/vimrc -O $HOME/.vimrc

  • 打开 Vim

    开拓Vim, 它将会自行安装插件. 请耐心等待它成功.
    只怕你能够利用上面包车型客车命令来自行安装.

    vim -E -u $HOME/.vimrc +qall

  • 享受你的Vim并个性化它吗!

 

③ 、近实时追寻(工程lucene-nearRealTime01

只是利用SearcherManager是不可能促成实时搜索的,因为只是更新的内部存款和储蓄器,而并不曾真正的付出。
在类IndexUtil.java中大家添加五个属性:

private NRTManager nrtMgr = null;
private IndexWriter writer;

对有关方法开始展览改造:

package cn.itcast.util;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.index.StaleReaderException;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NRTManager;
import org.apache.lucene.search.NRTManagerReopenThread;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.search.SearcherWarmer;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

public class IndexUtil {
    private String[] ids = {"1", "2", "3", "4", "5", "6"};
    //下面是邮件
    private String[] emails = {"aa@qq.com", "bb@sina.edu", "cc@yahu.org", "ss@sina.com", "dd@gmail.com", "ee@163.com"};
    //下面是邮件内容
    private String[] content = {
            "welcom to visited the space,I like football", 
            "hello boy, i like someone", 
            "come on baby like", 
            "first blood like", 
            "I like football,I like football", 
            "my girlfriend is so beatiful, every body like game"
    };
    private int[] attaches = {2,5,6,5,8,4};//附件数量
    //发件人名字
    private String[] names = {"Tom", "Jack", "goudan", "alibaba", "jerry", "kitty"};
    //邮件的日期
    private Date[] dates = null;

    private Directory directory = null;
    private Map<String, Float> scores = new HashMap<String, Float>();//新建一个Map,用来存储权值
    /*private static IndexReader reader = null;//声明一个IndexReader的属性*/
    private SearcherManager mgr = null;
    private NRTManager nrtMgr = null;
    private IndexWriter writer;

    public IndexUtil() {
        try {
            setDates();//设置日期
            scores.put("qq.com", 2.0f);//如果是"qq.com"结尾的索引则让其权值为2.0,注意:默认是1.0
            scores.put("sina.edu", 1.5f);
            directory = FSDirectory.open(new File("E:/myeclipse/Lucene/index"));
            writer = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35)));
            nrtMgr = new NRTManager(writer, new SearcherWarmer() {

                @Override
                public void warm(IndexSearcher arg0) throws IOException {
                    System.out.println("reopen");

                }
            });
            //重新打开的时候间隔最大为5.0,最小为0.025,0.025为25秒
            NRTManagerReopenThread reopen = new NRTManagerReopenThread(nrtMgr, 5.0, 0.025);
            reopen.setDaemon(true);
            reopen.setName("NrtManger Reopen Thread");
            reopen.start();//启动线程NRTManager的reopen线程
            mgr = nrtMgr.getSearcherManager(true);//允许所有更新
        } catch (IOException e) {
            e.printStackTrace(); 
        }
    }

    //创建索引
    public void index(){
        IndexWriter writer = null;
        try {
            writer = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35)));
            //此方法可将索引全部清空
            writer.deleteAll();
            Document document = null;
            for(int i = 0; i < ids.length; i++){
                document = new Document();
                //id需要存储,不需要加权、分词,email也需要存储,但不需要分词,有时候也需要加权
                //对于内容,我们不需要存储和加权,但需要分词。而名字需要存储,不需要分词和加权
                //这里我们先不对整型数据进行索引,后面再说
                document.add(new Field("id", ids[i], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
                document.add(new Field("email", emails[i], Field.Store.YES, Field.Index.NOT_ANALYZED));
                document.add(new Field("content", content[i], Field.Store.NO, Field.Index.ANALYZED));
                document.add(new Field("name", names[i], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));

                //为数字添加索引,第三个参数设置为true表示默认索引
                document.add(new NumericField("attach", Field.Store.YES, true).setIntValue(attaches[i]));
                //为日期添加索引
                document.add(new NumericField("date", Field.Store.YES, true).setLongValue(dates[i].getTime()));


                String et = emails[i].substring(emails[i].lastIndexOf("@") + 1);
                System.out.println(et);
                //加入权值
                if(scores.containsKey(et)){
                    document.setBoost(scores.get(et));
                }else{
                    document.setBoost(0.5f);
                }
                writer.addDocument(document);
            }
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (LockObtainFailedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(writer != null){
                try {
                    writer.close();
                } catch (CorruptIndexException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //查询
    public void query(){
        try {
            IndexReader reader = IndexReader.open(directory);
            //maxDoc 和 numDocs()方法的区别:maxDoc()返回索引中删除和未被删除的文档总数,
            //后者返回索引中未被删除的文档总数,通过reader可以有效获取文档的数量
            System.out.println("numDocs: " + reader.numDocs());
            System.out.println("maxDocs: " + reader.maxDoc());
            //查看被删除的索引
            System.out.println("deleteDocs : " + reader.numDeletedDocs());
            //记得用完之后关闭
            reader.close();

        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //删除索引
    public void delete(){
        IndexWriter writer = null;
        try {
            nrtMgr.deleteDocuments(new Term("id", "1"));//这里表示删除索引为1的id
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (LockObtainFailedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //更新索引
    public void update(){
        try {
            /* lucene并没有提供更新,这里的更新操作其实是如下两个操作的合集
             * 先删除之后再添加,所以不是在之前的位置更新
             * 测试之后我们会发现回收站中有一个索引
             * */
            Document document = new Document();
            document.add(new Field("id", "11", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
            document.add(new Field("email", emails[0], Field.Store.YES, Field.Index.NOT_ANALYZED));
            document.add(new Field("content", content[0], Field.Store.NO, Field.Index.ANALYZED));
            document.add(new Field("name", names[0], Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
            nrtMgr.updateDocument(new Term("id", "1"), document);
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (LockObtainFailedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void search01(){
        IndexReader reader;
        try {
            reader = IndexReader.open(directory);
            IndexSearcher searcher = new IndexSearcher(reader);
            TermQuery query = new TermQuery(new Term("content", "like"));//搜索内容中含有like的
            TopDocs tds = searcher.search(query, 10);
            for(ScoreDoc sd : tds.scoreDocs){
                Document doc = searcher.doc(sd.doc);
                //这里我们获取权值getBoost()的时候发现都是1.0,这是因为这里是获取的一个document,和原来的没有关系。
                //要想看其权值信息,可以使用luke工具
                //而这里的日期需要我们转换成日期格式
                System.out.println("(" + sd.doc + "权值:"+ doc.getBoost() + ")" + doc.get("name") + "[" + doc.get("email") + "]-->" 
                            + doc.get("id") + "-->" + doc.get("attach") + "-->" + doc.get("date"));
                reader.close();
            }
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //设置日期
    private void setDates(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dates = new Date[ids.length];
            dates[0] = sdf.parse("2015-02-15");
            dates[1] = sdf.parse("2015-03-01");
            dates[2] = sdf.parse("2015-05-18");
            dates[3] = sdf.parse("2015-09-05");
            dates[4] = sdf.parse("2015-12-15");
            dates[5] = sdf.parse("2015-08-29");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    public void search02(){
        IndexSearcher searcher = null;
        try {
            mgr.maybeReopen();//判断是否需要重新打开一个IndexSearcher
            searcher = mgr.acquire();
            TermQuery query = new TermQuery(new Term("content", "like"));//搜索内容中含有like的
            TopDocs tds = searcher.search(query, 10);
            for(ScoreDoc sd : tds.scoreDocs){
                Document doc = searcher.doc(sd.doc);
                System.out.println(doc.get("id") + "-->" + doc.get("name") + "[" + doc.get("email") + "]-->" 
                             + doc.get("attach") + "-->" + doc.get("date"));
            }
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                mgr.release(searcher);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void commit(){
        try {
            writer.commit();
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

说明:在方法IndexUtil中我们实例化了IndexWriter对象,同时利用NRTManager对象来取得SearcherManager对象,进而管理IndexSearcher。在deleteupdate方式中,直接使用NRTManager来展开连锁的操作,因为此目的达成了IndexSearcher的装有办法,所以大家不直接动用IndexSearcher了。在艺术search0第22中学我们应用办法maybeReopen看清是还是不是必要重新打开IndexSearcher,而那些打开的年华大家在艺术IndexUtil中设置的为25-4000秒之内。

测试:
测试时对testSearch02格局实行修改:

    @Test
    public void testSearch02(){
        IndexUtil util = new IndexUtil();
        for(int i = 0; i < 5; i++){
            util.search02();//这里我们让其执行5次
            System.out.println("************************");
            util.delete();
            if(i == 2){
                util.update();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

说明:测试结果:

1-->Tom[aa@qq.com]-->2-->1423929600000
2-->Jack[bb@sina.edu]-->5-->1425139200000
5-->jerry[dd@gmail.com]-->8-->1450108800000
6-->kitty[ee@163.com]-->4-->1440777600000
************************
reopen
2-->Jack[bb@sina.edu]-->5-->1425139200000
5-->jerry[dd@gmail.com]-->8-->1450108800000
6-->kitty[ee@163.com]-->4-->1440777600000
************************
2-->Jack[bb@sina.edu]-->5-->1425139200000
5-->jerry[dd@gmail.com]-->8-->1450108800000
6-->kitty[ee@163.com]-->4-->1440777600000
************************
reopen
2-->Jack[bb@sina.edu]-->5-->1425139200000
11-->Tom[aa@qq.com]-->null-->null
5-->jerry[dd@gmail.com]-->8-->1450108800000
6-->kitty[ee@163.com]-->4-->1440777600000
************************
2-->Jack[bb@sina.edu]-->5-->1425139200000
11-->Tom[aa@qq.com]-->null-->null
5-->jerry[dd@gmail.com]-->8-->1450108800000
6-->kitty[ee@163.com]-->4-->1440777600000
************************

此间大家是先实行查询,之后展开删减,同时在第③遍询问的时候进行更新,更新其实便是将事先id为1(删除的那条记下)更新为11,能够看占卜应的结果。而此刻我们再将去除和更新的部分注释掉,即:

util.delete();
if(i == 2){
    util.update();
}

威尼斯人线上娱乐,再也询问,发现并从未去除,那是因为除去只是在内部存款和储蓄器中实行,而并不曾交到。那里要留心的是:那里之所以叫近实时搜索,正是以此立异的时间是由线程序控制制,那里大家得以将休眠时间分别该为1秒和2秒(同时将mgr.maybeReopen();注解掉)来查阅效果。当然在这么些测试方法的终极加上

uti.commit();

才会将有关的翻新持久化。而比较之下SearcherManagerNRTManager不供给付出就能被寻找到,那样大家就足以在3个集合的时刻对索引实行翻新了。

未完待续。。。

支撑特色

宛如上表中,名字(name)中另行的想要去除,使用linq举办去重的不二法门,使用Distinct()根本无法达到须求。那么:

插件管理(Vundle)

在那份配置中,使用了Vundle作为插件管理器.
Vundle会自动接管 .vim
文件夹,全体配置好的插件将私下认可下载至~/.vim/bundle/
在应用从前请确定保障.vim文本夹干净. Vundle的插件安装需求触发 git clone
操作,搜索要求 curl 支持.

var list_distinct = list_Persons.GroupBy(c => c.name).Select(c => c.First());

布置(截取了一部分)

" let Vundle manage Vundle
Bundle 'gmarik/vundle'

" ============================================================================
" Active plugins
" You can disable or add new ones here:

" Plugins from github repos:

" Python and PHP Debugger
Bundle 'fisadev/vim-debug.vim'
" Better file browser
Bundle 'scrooloose/nerdtree'
" Code commenter
Bundle 'scrooloose/nerdcommenter'
" Class/module browser
Bundle 'majutsushi/tagbar'
" Code and files fuzzy finder
Bundle 'kien/ctrlp.vim'
" Extension to ctrlp, for fuzzy command finder
Bundle 'fisadev/vim-ctrlp-cmdpalette'
" Zen coding
Bundle 'mattn/emmet-vim'
" Git integration
Bundle 'motemen/git-vim'
" Tab list panel
Bundle 'kien/tabman.vim'

实在的趣味是基于某一列进行分组,然后拿走每一组的首先条数据,能够消除本次需求

辅助操作

命令 解释
:PluginList 列出所有Plugin
:PluginInstall(!) 安装/更新Plugin
:PluginSearch(!) foo 搜索foo相关的Plugin
:PluginClean(!) 清理未使用的Plugin
:PluginUpdate 更新插件

 

工程文件浏览(NE福睿斯DTree)

在那份配置中,
使用了NERDTree查看文件列表.
你可以在NE宝马7系DTree中浏览和开辟你文件系统中的目录或文件.
还足以拓展文件隐藏和过滤, 设置添加书签等.
在NETucsonDTree窗口输入?可获得操作指南. 这份配置中默许过滤掉了.pyc,
.git, .hg, .svn等公事或文件夹的突显.

配置

" auto open or close NERDTree
autocmd vimenter * if !argc() | NERDTree | endif
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTreeType") && b:NERDTreeType == "primary") | q | endif

" NERDTree -----------------------------

" toggle nerdtree display
map <F3> :NERDTreeToggle<CR>
" open nerdtree with the current file selected
nmap ,t :NERDTreeFind<CR>
" don;t show these file types
let NERDTreeIgnore = ['\.pyc$', '\.pyo$']

协理操作

快捷键 解释
F3 打开/关闭NERDTree
,t 打开NERDTree并选中当前文件

语法检查

在那份配置中,
使用Syntastic插件实行语法静态检查.
包蕴但不压制C/C++/Go/Python/Haskell/Ruby/JavaScript等.
在本配置中对JavaScript的静态检查采纳eslint,能够协理ES6及JSX等,
细节能够参见JSLint,
JSHint和ESLint的相持统一及Vim配置,
想要切换检查工具只要修改对应位置即可.

配置

" Syntastic ------------------------------

" show list of errors and warnings on the current file
nmap <leader>e :Errors<CR>
" turn to next or previous errors, after open errors list
nmap <leader>n :lnext<CR>
nmap <leader>p :lprevious<CR>
" check also when just opened the file
let g:syntastic_check_on_open = 1
" syntastic checker for javascript.
" eslint is the only tool support JSX.
" If you don't need write JSX, you can use jshint.
" And eslint is slow, but not a hindrance
" let g:syntastic_javascript_checkers = ['jshint']
let g:syntastic_javascript_checkers = ['eslint']
" don't put icons on the sign column (it hides the vcs status icons of signify)
let g:syntastic_enable_signs = 0
" custom icons (enable them if you use a patched font, and enable the previous 
" setting)
let g:syntastic_error_symbol = '✗'
let g:syntastic_warning_symbol = '⚠'
let g:syntastic_style_error_symbol = '✗'
let g:syntastic_style_warning_symbol = '⚠'

特性

封存时自动实行语法静态检查,方便的谬误提醒及灵活的可扩张性.

帮助操作

快捷键 解释
\e 打开错误列表
\n 移动到下一个错误位置
\p 移动到上一个错误位置

Git支持

在那份配置中,
使用vim-fugitivevim-signify做Git方面包车型地铁协理.
能够进行常用的git操作及优雅的情形提示等(近来补助githg).

配置

" Signify ------------------------------

" this first setting decides in which order try to guess your current vcs
" UPDATE it to reflect your preferences, it will speed up opening files
let g:signify_vcs_list = [ 'git', 'hg' ]
" mappings to jump to changed blocks
nmap <leader>sn <plug>(signify-next-hunk)
nmap <leader>sp <plug>(signify-prev-hunk)
" nicer colors
highlight DiffAdd           cterm=bold ctermbg=none ctermfg=119
highlight DiffDelete        cterm=bold ctermbg=none ctermfg=167
highlight DiffChange        cterm=bold ctermbg=none ctermfg=227
highlight SignifySignAdd    cterm=bold ctermbg=237  ctermfg=119
highlight SignifySignDelete cterm=bold ctermbg=237  ctermfg=167
highlight SignifySignChange cterm=bold ctermbg=237  ctermfg=227

支撑操作

快捷键 解释
:Git [args] 类似执行git命令一样
:Gstatus 类似git status.在列表中使用-添加/移除文件
:Gcommit [args] 类似 git commit
:Gmerge [args] 类似 git merge
:Gpull [args] 类似 git pull
:Gpush [args] 类似 git push
:Gvdiff [revision] 类似 git push 但是会切分窗口

更加多详细的操作能够行使 :help fugitive

Tag支持

在那份配置中,使用了Tagbar做Tag帮衬,能够来妥帖前文件中定义的类/变量等.

配置

" Tagbar -----------------------------

" toggle tagbar display
map <F4> :TagbarToggle<CR>
" autofocus on tagbar open
let g:tagbar_autofocus = 1

帮助操作

快捷键 解释
F4 打开Tag列表

超全自动补全

在这份配置中,
使用了Neocomplcache用作重中之重的机动补全插件.

配置

" NeoComplCache ------------------------------

" most of them not documented because I'm not sure how they work
" (docs aren't good, had to do a lot of trial and error to make 
" it play nice)

" Disable AutoComplPop.
let g:acp_enableAtStartup = 0
" Use neocomplcache.
let g:neocomplcache_enable_at_startup = 1
let g:neocomplcache_enable_ignore_case = 1
" Use smartcase.
let g:neocomplcache_enable_smart_case = 1
let g:neocomplcache_enable_auto_select = 1

let g:neocomplcache_enable_fuzzy_completion = 1
let g:neocomplcache_enable_camel_case_completion = 1
let g:neocomplcache_enable_underbar_completion = 1
let g:neocomplcache_fuzzy_completion_start_length = 1
let g:neocomplcache_auto_completion_start_length = 1
let g:neocomplcache_manual_completion_start_length = 1
" Set minimum syntax keyword length.
let g:neocomplcache_min_keyword_length = 1
let g:neocomplcache_min_syntax_length = 1
let g:neocomplcache_lock_buffer_name_pattern = '\*ku\*'
" complete with workds from any opened file
let g:neocomplcache_same_filetype_lists = {}
let g:neocomplcache_same_filetype_lists._ = '_'
" <TAB>: completion.
inoremap <expr><TAB>  pumvisible() ? "\<C-n>" : "\<TAB>"
" Define keyword.
if !exists('g:neocomplcache_keyword_patterns')
    let g:neocomplcache_keyword_patterns = {}
endif
let g:neocomplcache_keyword_patterns['default'] = '\h\w*'
" Plugin key-mappings.
inoremap <expr><C-g>     neocomplcache#undo_completion()
inoremap <expr><C-l>     neocomplcache#complete_common_string()
" <C-h>, <BS>: close popup and delete backword char.
inoremap <expr><C-h> neocomplcache#smart_close_popup()."\<C-h>"
inoremap <expr><BS> neocomplcache#smart_close_popup()."\<C-h>"
inoremap <expr><C-y>  neocomplcache#close_popup()
inoremap <expr><C-e>  neocomplcache#cancel_popup()

帮忙操作

快捷键 解释
<Tab> 使用Tab键进行待提示项目选择
<C-g> 取消补全
<C-l> 完成待补全项中共同的字符串
<C-h> 关闭待选项
<C-y> 关闭待选项
<C-e> 退出待选项
<BS> 关闭待选项

类Tmux的窗口采取

在那份配置中,使用了vim-choosewin举行窗口管理器.
援助类Tmux的操作.

配置

" Window Chooser ------------------------------

" mapping
nmap  -  <Plug>(choosewin)
" show big letters
let g:choosewin_overlay_enable = 1

支撑操作

快捷键 解释
开启窗口选择
– [ 选择上一个tab的窗口
– ] 选择下一个tab的窗口

越多操作能够采纳 :help choosewin

灵活的Tab管理

在那份配置中行使了TabMan展开Tab管理,能够拓展灵活切换与管理

配置

" TabMan ------------------------------

" mappings to toggle display, and to focus on it
let g:tabman_toggle = 'tl'
let g:tabman_focus  = 'tf'

支撑操作

快捷键 解释
tl 开启/关闭tab管理
tf 将光标移动到tab管理窗口

优雅的状态栏

在那份配置中,使用了Airline提供更加多景况栏扶助.

配置

" Airline ------------------------------

let g:airline_powerline_fonts = 1
let g:airline_theme = 'bubblegum'
"let g:airline#extensions#tabline#enabled = 1
"let g:airline#extensions#tabline#left_sep = ' '
"let g:airline#extensions#tabline#left_alt_sep = '|'
let g:airline#extensions#whitespace#enabled = 1

" to use fancy symbols for airline, uncomment the following lines and use a
" patched font (more info on the README.rst)
if !exists('g:airline_symbols')
   let g:airline_symbols = {}
endif

let g:airline_left_sep = ''
let g:airline_left_alt_sep = ''
let g:airline_right_sep = ''
let g:airline_right_alt_sep = ''
let g:airline_symbols.branch = ''
let g:airline_symbols.readonly = ''
let g:airline_symbols.linenr = ''

援救特色

能够来得分支,语法静态检查结果等.

电动插入尾部

在那份配置中写了个小函数依照新建的例外品类的文件,自动插入尾部,帮助python,
ruby, bash等.

马克down实时预览

在那份配置中,
使用了vim-instant-markdown和vim-markdown做马克down格式的援救,能够帮忙实时预览等个性.

此功用须要有node环境协助,能够推行 npm -g install instant-markdown-d
进行安装.

配置

" Vim-markdown ------------------------------

" Disabled automatically folding
let g:vim_markdown_folding_disabled=1
" LeTeX math
let g:vim_markdown_math=1
" Highlight YAML frontmatter
let g:vim_markdown_frontmatter=1

" Vim-instant-markdown -----------------

" If it takes your system too much, you can specify
" let g:instant_markdown_slow = 1
" if you don't want to manually control it
" you can open this setting
" and when you open this, you can manually trigger preview
" via the command :InstantMarkdownPreview
let g:instant_markdown_autostart = 0

帮衬操作

快捷键 解释
:InstantMarkdownPreview 手动触发markdown文件的预览

多游标选拔、编辑等

在那份配置中, 能够在高亮某单词时, 通过应用 Ctrl-n 或者 Ctrl-p
进行多游标选取, 然后实行编辑或涂改等操作.

神速文件查找

在那份配置中, 能够通过应用,R进展全文字笔迹检验索也许,r展开高效搜索,
也许在时下字符串上运用,wR以及,wr来进展全文字笔迹检验索或然高速查找.

迅猛注释

使用NERDCommenter插件达成快捷注释,
能够因而\ci进展快捷注释.

Python 支持

齐全的Python补助, 能够自动识别当前是系统环境或虚拟环境,
使用:Isort可智能对导入包实行排序, 使用:PymodeLintAuto可自动格式化.

除了上述列出的机能以外,
还有为数不少有利的天性,能够大大进步效能,在应用中慢慢体会呢!不寻常能够在tao12345666333/vim
on github 提issue


能够通过上边二维码订阅小编的稿子公众号【MoeLove】


相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图