Java fooling around notes: Lucene 5, Index basic additions and deletions check and change __lucene

Source: Internet
Author: User
Package cn;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.InputStreamReader;

Import Java.io.StringReader;
Import Org.apache.lucene.analysis.Analyzer;
Import Org.apache.lucene.analysis.TokenStream;
Import org.apache.lucene.document.Document;
Import Org.apache.lucene.document.Field.Store;
Import Org.apache.lucene.document.TextField;
Import Org.apache.lucene.index.DirectoryReader;
Import Org.apache.lucene.index.IndexReader;
Import Org.apache.lucene.index.IndexWriter;
Import Org.apache.lucene.index.IndexWriterConfig;
Import Org.apache.lucene.index.IndexWriterConfig.OpenMode;
Import Org.apache.lucene.index.Term;
Import Org.apache.lucene.search.BooleanClause.Occur;
Import Org.apache.lucene.search.BooleanQuery;
Import Org.apache.lucene.search.FuzzyQuery;
Import Org.apache.lucene.search.IndexSearcher;
Import Org.apache.lucene.search.MultiPhraseQuery;
Import Org.apache.lucene.search.PhraseQuery;
Import Org.apache.lucene.search.PrefixQuery;Import Org.apache.lucene.search.Query;
Import Org.apache.lucene.search.RegexpQuery;
Import Org.apache.lucene.search.ScoreDoc;
Import Org.apache.lucene.search.TermQuery;
Import Org.apache.lucene.search.TopDocs;
Import Org.apache.lucene.search.WildcardQuery;
Import Org.apache.lucene.search.highlight.Formatter;
Import Org.apache.lucene.search.highlight.Fragmenter;
Import Org.apache.lucene.search.highlight.Highlighter;
Import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
Import Org.apache.lucene.search.highlight.QueryScorer;
Import Org.apache.lucene.search.highlight.SimpleFragmenter;
Import Org.apache.lucene.search.highlight.SimpleHTMLFormatter;
Import Org.apache.lucene.store.Directory;
Import Org.apache.lucene.store.FSDirectory;
Import org.apache.lucene.util.Version;

Import Org.wltea.analyzer.lucene.IKAnalyzer;
		public class Curdindex {public static void main (string[] args) throws Exception {//add ();
		Update ();
		Delete (0);
		ShowAll (); QuerybyprefixquEry ("Loneliness");
	Querybyregexpquery ("Loneliness"); }//Add public static void Add () throws Exception {Directory directory = Fsdirectory.open (new File (System.getprope
		Rty ("User.dir") +file.separator+ "dir");
		Analyzer Analyzer = new Ikanalyzer ();
		Indexwriterconfig config = new Indexwriterconfig (version.lucene_40, analyzer);
		Config.setopenmode (Openmode.create_or_append);
		IndexWriter IW = new IndexWriter (directory, config);
		File Needindex = new file (System.getproperty ("User.dir") +file.separator+ "src" +file.separator+ "txt");
		int id = 1;
			For (File f:needindex.listfiles ()) {Document d = new document ();
			D.add (New TextField ("id", id+ "", Store.yes));
			D.add (New TextField ("title", F.getname (), store.yes));
			D.add (New TextField ("Content", Readtxt (f), Store.yes));
			Iw.adddocument (d);
			Iw.commit ();
		ID + +;
	} iw.close (); }//Update public static void Update () throws Exception {Directory directory = Fsdirectory.open (new File (SYSTEM.GETPR Operty ("User.dir") +file.separator+ "dir"));
		Analyzer Analyzer = new Ikanalyzer ();
		Indexwriterconfig config = new Indexwriterconfig (version.lucene_40, analyzer);
		Config.setopenmode (Openmode.create_or_append);
		IndexWriter IW = new IndexWriter (directory, config);
		File Needindex = new file (System.getproperty ("User.dir") +file.separator+ "src" +file.separator+ "txt");
		Document d = new document ();
		D.add (New TextField ("id", "1", Store.yes)); D.add (New TextField ("title", "2_" +needindex.listfiles () [0].getname (), store.yes));//Update directory D.add (new TextField ("
		Content ", Readtxt (Needindex.listfiles () [0]), store.yes));
		Iw.updatedocument (New Term ("id", "1"), d);//update index with ID equal to 1 iw.commit ();
	Iw.close (); }//Remove public static void Delete (int type) throws Exception {Directory directory = Fsdirectory.open (new File (Syst
		Em.getproperty ("User.dir") +file.separator+ "dir");
		Analyzer Analyzer = new Ikanalyzer ();
		Indexwriterconfig config = new Indexwriterconfig (version.lucene_40, analyzer); Config.setopenmode (OPenmode.create_or_append);
		IndexWriter IW = new IndexWriter (directory, config);
		if (type = = 0) {//delete all Iw.deleteall ();
		}else {iw.deletedocuments (new Term ("id", "1");//delete} iw.commit () According to the index id=1;
	Iw.close (); //query//1, List all public static void ShowAll () throws Exception {Directory directory = Fsdirectory.open (new File (S)
		Ystem.getproperty ("User.dir") +file.separator+ "dir");
		Indexreader reader = directoryreader.open (directory);
			for (int i = 0; i < Reader.numdocs (); i + +) {Document d = reader.document (i);
			System.out.println ("I:" +i);
			SYSTEM.OUT.PRINTLN ("ID:" +d.get ("id"));
			System.out.println ("title:" +d.get ("title"));
			
		System.out.println ("Content:" +d.get ("Content")); }//2, keyword query termquery public static void Querybykeyword (String keyword) throws Exception {Directory directory
		= Fsdirectory.open (New File ("G:\\eclipseworkspace\\lucence\\dir"));
		Indexreader read = directoryreader.open (directory); Indexsearcher searcher =New Indexsearcher (read);
		Query query = new Termquery (new Term ("content", keyword));
		Topdocs top = searcher.search (query, 12);
		System.out.println ("Get" +top.totalhits+ "record");
		scoredoc[] Scoredocs = Top.scoredocs;
			for (Scoredoc scoredoc:scoredocs) {Document doc = Searcher.doc (scoredoc.doc);
			System.out.println (Doc.get ("id"));
			System.out.println (Doc.get ("title"));
		System.out.println (Doc.get ("content"));
	} read.close (); }//3, prefix query prefixquery for example: loneliness * public static void Querybyprefixquery (String keyword) throws Exception {Directory
		Directory = Fsdirectory.open (new File ("G:\\eclipseworkspace\\lucence\\dir"));
		Indexreader read = directoryreader.open (directory);
		Indexsearcher searcher = new Indexsearcher (read);
		Query query = new Prefixquery (new Term ("content", keyword));
		Topdocs top = searcher.search (query, 12);
		System.out.println ("Get" +top.totalhits+ "record");
		scoredoc[] Scoredocs = Top.scoredocs; for (Scoredoc scoredoc:scoredocs) {Document doc =Searcher.doc (Scoredoc.doc);
			System.out.println (Doc.get ("id"));
			System.out.println (Doc.get ("title"));
			System.out.println (Doc.get ("content"));
		Markkeyword (query, doc);
	} read.close (); //4, wildcard query Wildcardquery for example: * lonely * public static void Querybywildcardquery (String keyword) throws Exception {Direc
		Tory directory = Fsdirectory.open (new File ("G:\\eclipseworkspace\\lucence\\dir"));
		Indexreader read = directoryreader.open (directory);
		Indexsearcher searcher = new Indexsearcher (read);
		Query query = new Wildcardquery (new Term ("content", keyword));
		Topdocs top = searcher.search (query, 12);
		System.out.println ("Get" +top.totalhits+ "record");
		scoredoc[] Scoredocs = Top.scoredocs;
			for (Scoredoc scoredoc:scoredocs) {Document doc = Searcher.doc (scoredoc.doc);
			System.out.println (Doc.get ("id"));
			System.out.println (Doc.get ("title"));
			System.out.println (Doc.get ("content"));
		Markkeyword (query, doc);
	} read.close (); //5, fuzzy query fuzzyquery with percent, such as:% of PUBlic static void Querybyfuzzyquery (String keyword) throws Exception {Directory directory = Fsdirectory.open (new File ("
		G:\\eclipseworkspace\\lucence\\dir "));
		Indexreader read = directoryreader.open (directory);
		Indexsearcher searcher = new Indexsearcher (read);
		Query query = new Fuzzyquery (new Term ("content", keyword));
		Topdocs top = searcher.search (query, 12);
		System.out.println ("Get" +top.totalhits+ "record");
		scoredoc[] Scoredocs = Top.scoredocs;
			for (Scoredoc scoredoc:scoredocs) {Document doc = Searcher.doc (scoredoc.doc);
			System.out.println (Doc.get ("id"));
			System.out.println (Doc.get ("title"));
			System.out.println (Doc.get ("content"));
		Markkeyword (query, doc);
	} read.close (); }//6, regular query regexpquery public static void Querybyregexpquery (String keyword) throws Exception {Directory Director
		y = Fsdirectory.open (New File ("G:\\eclipseworkspace\\lucence\\dir"));
		Indexreader read = directoryreader.open (directory); Indexsearcher searcher = new IndexseaRcher (read);
		Query query = new Regexpquery (new Term ("content", keyword));
		Topdocs top = searcher.search (query, 12);
		System.out.println ("Get" +top.totalhits+ "record");
		scoredoc[] Scoredocs = Top.scoredocs;
			for (Scoredoc scoredoc:scoredocs) {Document doc = Searcher.doc (scoredoc.doc);
			System.out.println (Doc.get ("id"));
			System.out.println (Doc.get ("title"));
			System.out.println (Doc.get ("content"));
		Markkeyword (query, doc);
	} read.close (); }//7, Boolean query booleanquery public static void Querybybooleanquery (String keyword) throws Exception {Directory D
		Irectory = Fsdirectory.open (New File ("G:\\eclipseworkspace\\lucence\\dir"));
		Indexreader read = directoryreader.open (directory);
		Indexsearcher searcher = new Indexsearcher (read);
		booleanquery bool = new Booleanquery (); Bool.add (New Regexpquery ("content", keyword), occur.must);//This query condition must satisfy the Bool.add (new Fuzzyquery ("New Term" (" Content ", keyword), occur.must_not);//This query condition must have no bool.add (new wildcardQuery (new Term ("content", keyword), occur.should);//This inquiry condition may have topdocs top = Searcher.search (bool, 12);
		System.out.println ("Get" +top.totalhits+ "record");
		scoredoc[] Scoredocs = Top.scoredocs;
			for (Scoredoc scoredoc:scoredocs) {Document doc = Searcher.doc (scoredoc.doc);
			System.out.println (Doc.get ("id"));
			System.out.println (Doc.get ("title"));
			System.out.println (Doc.get ("content"));
		Markkeyword (bool, doc);
	} read.close (); //8, phrase query public static void Querybyphrasequery () throws Exception {Directory directory = Fsdirectory.open (new
		File ("G:\\eclipseworkspace\\lucence\\dir"));
		Indexreader read = directoryreader.open (directory);
		Indexsearcher searcher = new Indexsearcher (read);
		Phrasequery PQ = new Phrasequery ();
		Pq.setslop (2);//set interval before multiple Term pq.add (new Term ("content", "we");//orderly, in accordance with the record Pq.add (new Term ("content", "you");
		Topdocs top = Searcher.search (PQ, 12);
		System.out.println ("Get" +top.totalhits+ "record"); scoredoc[] Scoredocs = TOP.SCoredocs;
			for (Scoredoc scoredoc:scoredocs) {Document doc = Searcher.doc (scoredoc.doc);
			System.out.println (Doc.get ("id"));
			System.out.println (Doc.get ("title"));
			System.out.println (Doc.get ("content"));
		Markkeyword (PQ, doc);
	} read.close (); }//9, multi-phrase query public static void Querybymultiphrasequery () throws Exception {Directory directory = Fsdirectory.ope
		N (New File ("G:\\eclipseworkspace\\lucence\\dir"));
		Indexreader read = directoryreader.open (directory);
		Indexsearcher searcher = new Indexsearcher (read);
		Multiphrasequery multiphrasequery = new Multiphrasequery ();
		Multiphrasequery.add (New Term ("content", "we"));
		Multiphrasequery.add (New Term ("title", "You");
		Topdocs top = Searcher.search (Multiphrasequery, 12);
		System.out.println ("Get" +top.totalhits+ "record");
		scoredoc[] Scoredocs = Top.scoredocs;
			for (Scoredoc scoredoc:scoredocs) {Document doc = Searcher.doc (scoredoc.doc);
			System.out.println (Doc.get ("id")); System.out.println (Doc.get ("TitLe "));
			System.out.println (Doc.get ("content"));
		Markkeyword (Multiphrasequery, doc);
	} read.close (); }//TXT text public static String readtxt (file file) {try {bufferedreader br = new BufferedReader (New Inputstrea
			Mreader (new FileInputStream (file), "UTF-8"));
			String str = NULL;
			StringBuffer SBF = new StringBuffer ();
			while (str = Br.readline ())!= null) {sbf.append (str);
			} br.close ();
		return sbf.tostring ();
			catch (Exception e) {e.printstacktrace ();
		Return ""; /** * Set search results Highlighting "" Wrapped * @param Query method * @param d documents identified * @throws invalidtokenoffsetsexception * @thr OWS Exception */public static void Markkeyword (query query, Document D) throws exception{Analyzer Analyzer = NE
		W Ikanalyzer ();  
	    Queryscorer scorer = new Queryscorer (query);  
		Formatter Formatter = new Simplehtmlformatter ("" "," "");  
		Highlighter Highlight = new highlighter (formatter,scorer); Fragmenter fragmenter = new SimplefragmeNter (888);//Highlight string length Highlight.settextfragmenter (fragmenter);
		Tokenstream Tokenstream = Analyzer.tokenstream ("Content", New StringReader (D.get ("content"));
		String highlightstr = highlight.getbestfragment (Tokenstream, D.get ("content"));
		System.out.println ("Show search results location");
	System.out.println (HIGHLIGHTSTR);
 }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.