A SOLR search instance, adding and removing changes + highlighting + paging

Source: Internet
Author: User
Tags solr

Today personal Coding module test, so spare time to continue to study SOLR, and then incidentally wrote an example, casually, SOLR really not familiar, look forward to know love search friends, and common progress.

1. Configure the Schema.xml file [solr\collection1\conf\ directory]

Because schema defines some field by default, we select the [Id,title,description, author] Property here, configure the ID primary key type as String, and a few other type to configure the IK word breaker as a custom

   <field name= "id" type= "string" indexed= "true" stored= "true" required= "true" multivalued= "false"/>    < Field name= "title" Type= "Text_ik" indexed= "true" stored= "true" multivalued= "true"/>   <field name= " Description "type=" Text_ik "indexed=" true "stored=" true "/>   <field name=" author "type=" Text_ik "indexed=" True "stored=" true "/>   <field name=" keywords "type=" Text_ik "indexed=" true "stored=" true "/>

The IK word breaker is defined as follows

    <!--define IK parts-to-    <fieldtype name= "Text_ik" class= "SOLR. TextField ">        <!--the word breaker at index time--          <analyzer type=" index "ismaxwordlength=" false "class=" Org.wltea.analyzer.lucene.IKAnalyzer "/>        <!--word breaker--        <analyzer type=" Query " Ismaxwordlength= "true" class= "Org.wltea.analyzer.lucene.IKAnalyzer"/>    </fieldType>

2. Write the SOLR action class SEARCHENGINE.JAVA,SOLRJ operation index See article: http://www.cnblogs.com/dennisit/p/3623974.html
3. Show Solrj Search highlighting here

/** * SOLRJ Search Highlighting * * @author pudongping * * @param server * SOLR client * @param queryString * Query String * @param pagenum * Pagination page number * @param pagesi Ze * Display size per page * @return */public static page<qzonearticle> Querycomhighlight (Solrs        Erver server, String queryString, int pagenum,int pageSize) {solrquery query = new Solrquery ();        Query.setquery (queryString); Query.sethighlight (TRUE);//Turn on the Highlight function Query.addhighlightfield ("description");//Highlight field Query.addhighlightfield ("Key        Words "); Query.sethighlightsimplepre ("<font color= ' Red ' >");//Render label query.sethighlightsimplepost ("</font>");//        Render Label Query.setstart ((pageNum-1) *pagesize);        Query.setrows (pageSize);        Queryresponse response = null;        try {response = server.query (query); } catch (Solrserverexception e) {E.PRintstacktrace ();        return null;                }//Query result set solrdocumentlist lists = Response.getresults ();                Object result set list<qzonearticle> items = new arraylist<qzonearticle> ();                Total number of records queried long TotalRow = long.valueof (Response.getresults (). Getnumfound ()). Intvalue ();                String tmpid = "";         Map<string,map<string,list<string>>> highlightmap=response.gethighlighting ();             for (Solrdocument solrdocument:lists) {qzonearticle at = new Qzonearticle ();             Tmpid=solrdocument.getfieldvalue ("id"). toString ();             At.setid (TMPID);             At.setauthor (Solrdocument.getfieldvalue ("Author"). toString ());             List<string> Desclist=highlightmap.get (tmpid). Get ("description");             List<string> Keywslist=highlightmap.get (tmpid). Get ("keywords"); if (Desclist!=null && desclist.size () >0) {At.setdescRiption (desclist.get (0)); }else{//Gets and sets the highlighted field title At.setdescription (Solrdocument.getfieldvalue ("description"). Tostr             ing ());             } if (Keywslist!=null && keywslist.size () >0) {at.setkeywords (keywslist.get (0));             }else{at.setkeywords (solrdocument.getfieldvalue ("keywords"). toString ());         } items.add (at);            }//Fill Page object return new Page<qzonearticle> (Pagenum, PageSize, TotalRow, items); }

Search highlighting is found in the record field of the keyword, and then append the prefix, re-populate the object, here is the two steps, the first set of the Highlight field, the second step of the query results append render mark, fill the object. So this can be extracted and written as a common method.

4. Extract the highlight operation to achieve a common method

    /** * Based on keyword query [test pass-using SOLR internal conversion mechanism] * @param <T> * @param server SOLR client * @param keyword    Search keywords * @param pagenum current page number * @param pageSize size per page * @param clzz Object Type * @return */ public static <T>Page<T> Queryhighter (Solrserver server,string solrql, int pagenum,int Pagesize,li St<string> Hlfield, String pretag,string posttag,class<t> clzz,string idname) {SolrQuery query = new SO        Lrquery ();        Query.setquery (SOLRQL);        Sets the highlight query.sethighlight (true);        Add a highlighted field for (String Hlf:hlfield) {Query.addhighlightfield (HLF);        }//Render label query.sethighlightsimplepre (Pretag);        Query.sethighlightsimplepost (Posttag);        Paged Query Query.setstart ((pageNum-1) *pagesize);        Query.setrows (pageSize);        Queryresponse response = null;        try {response = server.query (query); } catch (SolrserverexceptiOn e) {e.printstacktrace ();        return null;        }//The total number of records queried long TotalRow = long.valueof (Response.getresults (). Getnumfound ()). Intvalue ();                Query result set list<t> items = new arraylist<t> ();        Query result set Solrdocumentlist solrdocuments = Response.getresults ();            try {Object obj = null;            Method m = null;            Class<?> FieldType = null;            Map<string,map<string,list<string>>> highlightmap=response.gethighlighting ();                    for (solrdocument solrdocument:solrdocuments) {obj = Clzz.newinstance ();            collection<string> FieldNames = Solrdocument.getfieldnames (); Get all the property names for (String fieldname:fieldnames) {//need to be described is the returned result set of FieldNames () than the generic                        More field[] Filedarrays = Clzz.getdeclaredfields ();      Get all properties in a class                  for (field f:filedarrays) {//If the Entity property name and the field name in the query return set are consistent, populate the corresponding set method if (F.getname (). Equals (FieldName)) {//acquired  Property name//private java.lang.String com.test.model.Article.id f =                                                                    Clzz.getdeclaredfield (FieldName);                                Property type//private java.lang.String com.test.model.Article.id                                                                    FieldType = F.gettype ();                                                                Constructs the Set method name SetId String Dynamicsetmethod = Dynamicmethodname (F.getname (), "set"); Get method//public void Com.test.model . Article.setid (java.lang.String) m = clzz.geTMethod (Dynamicsetmethod, FieldType); Gets the value of Log.info (F.getname () + "-" + dynamicsetmethod+ "=" + Fieldtype.cast (solrdocume                                                                Nt.getfieldvalue (FieldName));                                                                Get FieldType Type FieldType = Getfiletype (FieldType); Gets the attribute M.invoke (obj, Fieldtype.cast (Solrdocument.getfieldvalue (f                                                                (Ieldname)));                                        for (String Hl:hlfield) {if (Hl.equals (FieldName)) {                                        String IdV = Solrdocument.getfieldvalue (idname). toString ();                                        List<string> Hlflist=highlightmap.get (IDV). get (FieldName); if (null!=hlflist && hlflist. Size () >0) {//Highlight add M.invoke (obj,                                        Fieldtype.cast (hlflist.get (0))); }else{//Normal add M.invoke (obj, Fieldtyp                                        E.cast (Solrdocument.getfieldvalue (FieldName)));                                                                                            }                                    }                                }                                            }                                                    }            } items.add (Clzz.cast (obj));            }} catch (Exception e) {log.error ("Highlighter query error." + E.getmessage (), E);        E.printstacktrace ();    }//Fill Page object return new Page<t> (Pagenum, PageSize, TotalRow, items); } public static Class<?  > Getfiletype (class<?> fieldtype) {//if it is an int, float and other basic types, you need to transform if (Fieldtype.equals (Integer.type))        {return integer.class;        } else if (Fieldtype.equals (Float.type)) {return float.class;        } else if (Fieldtype.equals (Double.type)) {return double.class;        } else if (Fieldtype.equals (Boolean.type)) {return boolean.class;        } else if (Fieldtype.equals (Short.type)) {return short.class;        } else if (Fieldtype.equals (Long.type)) {return long.class;        } else if (Fieldtype.equals (String.class)) {return string.class;        }else if (fieldtype.equals (Collection.class)) {return collection.class;    } return null; }

It is important to note that the method definition here is not perfect, because the reflected property may be a collection, so you need to make more precise judgments before taking advantage of the reflection transformation, which is a simple type of attribute in the entity object, so this method can be processed.

5.junit Test

Package Com.test.search;import Java.util.arraylist;import Java.util.list;import java.util.uuid;import Org.apache.solr.client.solrj.solrserver;import Org.junit.before;import Org.junit.test;import Com.plugin.page.Page ; Import Com.plugin.solr.client.solrclient;import Com.plugin.solr.engine.solrenginehandler;import        Com.test.model.qzonearticle;public class Solrtest {private Solrserver server;         @Before public void init () {String Solrurl = "HTTP://LOCALHOST:8888/SOLR";    Server = Solrclient.gethttpsolrserver (Solrurl);        } @Test public void Qzoneadd () {list<qzonearticle> lists = new arraylist<qzonearticle> ();        Qzonearticle qz1 = new Qzonearticle ();        Qz1.setid (Uuid.randomuuid (). toString ());        Qz1.setauthor ("Sujonin");        Qz1.setdescription ("Java program ape, Love Music, love life, Love Text");                Qz1.setkeywords ("Java, music, life, writing");        Qzonearticle qz2 = new Qzonearticle ();        Qz2.setid (Uuid.randomuuid (). toString ()); Qz2.setauthoR ("Lin Yunxi");        Qz2.setdescription ("Text control, I have no regrets, vertical is the love of tears from the People");                Qz2.setkeywords ("text");        Lists.add (QZ1);                Lists.add (QZ2);    Searchengine.addbeans (server, lists);        } @Test public void Qzonedelid () {String id = "4F1B6B87-C824-4E38-A431-9A8F50E7AF0C";    Solrenginehandler.deletebyid (server, "id", id);        } @Test public void Qzonedelids () {list<string> ids = new arraylist<string> ();        Ids.add ("d026e3ef-b89a-4ce2-9fbb-aa195ed2070b");        Ids.add ("9deb98ca-5a65-424d-95ad-91e87c2bde2c");        Ids.add ("5576650d-5517-43d5-987c-6d7135588e1f");    Solrenginehandler.deletebyids (server, "id", IDS);    } @Test public void Qzonedelall () {solrenginehandler.deleteallindex (server);        } @Test public void Qzonehlquery () {String SOLRQL = "keywords: text";        list<string> hlfields = new arraylist<string> ();        Hlfields.add ("description"); Hlfields.add ("KEywords ");        String Pretag = "<font color= ' red ' >";        String Posttag = "</font>"; page<qzonearticle> page = Searchengine.queryhighter (SERVER,SOLRQL, 1, Hlfields, Pretag, PostTag, QzoneArticle        . class, "id");    Formatprint (page, SOLRQL);        }//test passed @Test public void Qzonecommonhlquery () {String SOLRQL = "description: Text";        page<qzonearticle> page = searchengine.querycomhighlight (server, SOLRQL, 1, 10);    Formatprint (page, SOLRQL);        } @Test public void Qzonequery () {String SOLRQL = "literal";        page<qzonearticle> page = Searchengine.query (SERVER,SOLRQL, 1, 10,qzonearticle.class);    Formatprint (page, SOLRQL);        } @Test public void Qzoneupdate () {qzonearticle QZ = new Qzonearticle ();        Qz.setid ("5576650d-5517-43d5-987c-6d7135588e1f");        Qz.setauthor ("Lin Yunxi");        Qz.setdescription ("Text control, I have no regrets, vertical is the love of tears from the People");        Qz.setkeywords ("text"); SearchEngine. Updatebean (server, QZ, "id");    } @Test public void Pingsolr () {System.out.println ("ping solr Result:" +solrenginehandler.ping (server));                 } public void Formatprint (page<qzonearticle> page,string solrql) {System.out.println ("query:" + SOLRQL + "\t\t page" + page.getpagenum () + "/" + page.gettotalpage () + ", Total found" + Pag                E.gettotalrow () + "record in accordance with". \ n ");            For (Qzonearticle Qz:page.getItems ()) {System.out.println ("Author:" + Qz.getauthor ());            System.out.println ("description:" + qz.getdescription ());        System.out.println ("Keyword:" + qz.getkeywords () + "\ n"); }    }    }

The search result set is shown below:

Query: Keywords: text        page 1/1, a total of 2 matching records were found. Author: Lin Yunxi Description: <font color= ' red ' > Text </font> control, I have no regrets, vertical is the love of tears from people keywords: <font color= ' Red ' > Text </font> Author: Sujonin Description: Java program ape, Love Music, love life, Love <font color= ' red ' > Text </font> keywords: java, music, life, <font color= ' red ' > Text </font>

A SOLR search instance, adding and removing changes + highlighting + paging

Related Article

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.