The Deftype of Solr has dismax/edismax two species, the difference between the two, see: http://blog.csdn.net/duck_genuine/article/details/8060026
The following example is used to demonstrate the following scenario:
There is a Web site in which the results of user queries need to be sorted as follows:
- VIP billing information needs to be at the forefront of free information
- The higher the CTR, the more forward.
- The later the release time, the more forward
This sort of query is not done using the order by of the normal query results, and it is necessary to use SOLR's Deftype.
Practice:
1, first look at the definition of Schema.xml:
<?xml version= "1.0"? ><schema name= "Sample5" version= "1.1" > <fieldtype name= "string" class= "SOLR. Strfield "sortmissinglast=" true "omitnorms=" true "/> <fieldtype name=" Long "class=" SOLR. Trielongfield "precisionstep=" 0 "positionincrementgap=" 0 "/> <fieldtype name=" tdate "class=" SOLR. Triedatefield "precisionstep=" 6 "positionincrementgap=" 0 "/> <fieldtype name=" int "class=" SOLR. Trieintfield "precisionstep=" 0 "positionincrementgap=" 0 "/> <fieldtype name=" float "class=" SOLR. Triefloatfield "precisionstep=" 0 "positionincrementgap=" 0 "/> <fieldtype name=" Double "class=" SOLR. Triedoublefield "precisionstep=" 0 "positionincrementgap=" 0 "/> <fieldtype name=" boolean "class=" SOLR. Boolfield "sortmissinglast=" true "/> <fieldtype name=" binary "class=" SOLR. Binaryfield "/> <fieldtype name=" text_cn "class=" SOLR. TextField "> <analyzer type=" index "class=" Org.wltea.analyzer.lucene.IKAnalyzer "usesmart=" false "/> <analyzer type= "Query" class= "Org.wltea.analyzer.lucene.IKAnalyzer" usesmart= "true"/> <analyzer> ; <tokenizer class= "SOLR. Keywordtokenizerfactory "/> <filter class=" SOLR. Lowercasefilterfactory "ignorecase=" true "/> </analyzer> </fieldType> <!--General--> ; <fields> <field name= "id" type= "Long" indexed= "true" stored= "true" multivalued= "false" required= "true"/> ; <field name= "Subject" type= "TEXT_CN" indexed= "true" stored= "true"/> <field name= "content" type= "TEXT_CN" Indexed= "true" stored= "true"/> <field name= "RegionID" type= "int" indexed= "true" stored= "true"/> & Lt;field name= "Region" type= "TEXT_CN" indexed= "true" stored= "true"/> <field name= "categoryId" type= "int" ind Exed= "true" stored= "true"/> <field name= "category" Type= "TEXT_CN" indexed= "true" stored= "true"/> <field name= "Price" type= "Float "indexed=" true "stored=" true "/> <field name=" createtime "type=" Tdate "indexed=" true "stored=" true "/&G T <field name= "point" type= "Long" indexed= "true" stored= "true"/> <field name= "VIP" Type= "boolean" indexed= " True "stored=" true "/> <field name=" _version_ "type=" Long "indexed=" true "stored=" true "/> <field Name= "SearchText" type= "TEXT_CN" indexed= "true" stored= "false" multivalued= "true"/> </fields> <cop Yfield source= "Subject" dest= "SearchText"/> <copyfield source= "content" dest= "SearchText"/> <copyfield source= "Region" dest= "SearchText"/> <copyfield source= "category" dest= "SearchText"/> <!--field To determine and enforce document uniqueness. -<uniqueKey>id</uniqueKey> <!--field for the Queryparser-to-use if an explicit fieldname I S absent-<defaultSearchField>searchText</defaultSearchField> <!--solrqueryparser configuration:defaultoperator= "And|or"-<solrqueryparser defaultoperator= "and"/ ></schema>
Description
A) a copyfield:searchtext is defined in this field: Subject+content+region+category, which is set as the default query field. This means that the contents of the four fields are queried by default when querying.
b) Set the Solrqueryparser to and, in fact, in most cases, we are accustomed to using and as a conditional query, rather than or
c) text_cn in the field type: Usesmart
<analyzer type= "index" class= "Org.wltea.analyzer.lucene.IKAnalyzer" usesmart= "false"/> <analyzer type = "Query" class= "Org.wltea.analyzer.lucene.IKAnalyzer" usesmart= "true"/>
This means: Usesmart =true, the word breaker uses intelligent segmentation Strategy, =false uses fine-grained segmentation. Detailed, can download IK word breaker's source code to look.
2, add a query handler to Solrconfig.xml <config/>:
<requesthandler name= "/browse" class= "SOLR. Searchhandler "default=" true "> <lst name=" Defaults "> <str name=" Deftype ">edismax</str > <str name= "BF" > sum (Linear (vip,1000,0), linear (sqrt (log (linear)), point,1,2), 100,0 (log ( MS (Createtime))) </str> <!--<str name= "PF" > searchtext </str> <str Name= "QF" > subject^1 content^0.8 </str>--> </lst> </requestHandler>
Description
A) The default= "true" above means set as the default query handler (remember to remove the default= "true" from the original standard)
b) See the paragraph that has been annotated:
<!--<str name= "PF" > searchtext </str> <str name= "QF" > subject^1 content^ 0.8 </str>-->
This is simply not using the BF sort weighting method, can be used to cope with simple sorting, specific PF/QF use, can be online search application. The functionality shown here is relatively "complex" and does not apply to it.
c) See this formula:
SUM (Linear (vip,1000,0), linear (sqrt (log (linear)), point,1,2), 100,0 (log (MS (sqrt))))
The function definition and meaning in the formula, can refer to:
Official documents:
Http://wiki.apache.org/solr/FunctionQuery
English Description:
http://mxsfengg.iteye.com/blog/352191
Here the function means:
- If it is VIP information = value +1000, non-VIP information = value +0
- The value range for click-Through (point) is: between 50~500
- Release time (createtime) value range: 50 or less
The above three values are summed to derive the highest order from highest to lowest
3. Java Bean:
Package Com.my.entity;import Java.util.date;import Org.apache.solr.client.solrj.beans.field;public class Item {@ Field Private long ID; @Field private String subject; @Field private String content; @Field private int RegionID; @Field private int categoryId; @Field private float price; @Field private Date Createtime; @Field private Long Point; @Field Private Boolean VIP; Public long GetId () {return id; } public void SetId (long id) {this.id = ID; } public String Getsubject () {return subject; } public void Setsubject (String subject) {this.subject = subject; } public String GetContent () {return content; The public void SetContent (String content) {this.content = content; } public int Getregionid () {return regionid; } public void Setregionid (int regionid) {This.regionid = RegionID; } public int Getcategoryid () {RetuRN CategoryId; } public void Setcategoryid (int categoryId) {This.categoryid = CategoryId; } public float GetPrice () {return price; } public void Setprice (float price) {this.price = Price; Public Date Getcreatetime () {return createtime; } public void Setcreatetime (Date createtime) {this.createtime = Createtime; } public Long GetPoint () {return point; The public void SetPoint (Long point) {this.point = point; } public boolean Isvip () {return VIP; } public void Setvip (Boolean vip) {THIS.VIP = VIP; }}
4. Java Test Code:
Package Com.my.solr;import Java.io.ioexception;import Java.util.arraylist;import java.util.calendar;import Java.util.date;import Java.util.hashmap;import Java.util.iterator;import Java.util.list;import Org.apache.solr.client.solrj.solrquery;import Org.apache.solr.client.solrj.solrquery.order;import Org.apache.solr.client.solrj.solrquery.sortclause;import org.apache.solr.client.solrj.SolrServerException; Import Org.apache.solr.client.solrj.impl.httpsolrserver;import Org.apache.solr.client.solrj.impl.xmlresponseparser;import Org.apache.solr.client.solrj.response.FacetField; Import Org.apache.solr.client.solrj.response.facetfield.count;import Org.apache.solr.client.solrj.response.queryresponse;import Org.apache.solr.common.params.analysisparams;import Org.apache.solr.common.params.commonparams;import Org.apache.solr.common.params.facetparams;import Org.apache.solr.common.util.namedlist;import Org.apache.solr.common.util.simpleorderedmap;import Com.my.entity.item;public class TESTSOLR {pRivate static Hashmap<integer, string> mapRegion = new Hashmap<integer, string> (); private static Hashmap<integer, string> mapcategory = new Hashmap<integer, string> (); @SuppressWarnings ("unchecked") public static void main (string[] args) throws IOException, Solrserverexceptio n {//------------------------------------------------------//Set map//------------------------- -----------------------------mapregion.put (1, "Luohu District"); Mapregion.put (2, "Nanshan District"); Mapregion.put (3, "Longgang District"); Mapregion.put (4, "Futian District"); Mapcategory.put (1, "single room"); Mapcategory.put (2, "2 bedroom 1 Hall"); Mapcategory.put (3, "3 bedroom 2 Hall"); Mapcategory.put (4, "1 bedroom 1 hall"); String url = "Http://localhost:8983/solr/sample5"; Httpsolrserver core = new Httpsolrserver (URL); Core.setmaxretries (1); Core.setconnectiontimeout (5000); Core.setparser (New Xmlresponseparser ()); Binary parser is useD by//default core.setsotimeout (1000); Socket read Timeout core.setdefaultmaxconnectionsperhost (100); Core.setmaxtotalconnections (100); Core.setfollowredirects (FALSE); Defaults to False core.setallowcompression (true); ------------------------------------------------------//Remove all data//---------------------------- --------------------------core.deletebyquery ("*:*"); list<item> items = new arraylist<item> (); Items.Add (Makeitem (items.size () + 1, "Longcheng apartment one bedroom, one room", "Luxury City City apartment 1 Room 1 hall, twist Bag Stay", 1, 1, 1200f, ten, false)); Items.Add (Makeitem (items.size () + 1, "Xing Xin dormitory Building 1 Room 0 Hall", "Medium decoration recruit female co-rental", 1, 1, 1000f, one, false)); Items.Add (Makeitem (items.size () + 1, "Silino House village new dormitory building single room", "Invincible decoration only Female", 2, 1, 1000f, 2, true)); Items.Add (Makeitem (items.size () + 1, "Dafen Letter and Aegean Metro Exit 2 Room 1 Hall", "Subway port + Travel convenience = Home preferred", 3, 2, 2000f, 5, false)); Items.Add (Makeitem (ITEMS.SIze () + 1, "Longgang Regal Garden 3 Room 2 Hall for lease", "just 5 minutes from the subway exit, quick seconds to Kill", 3, 3, 4500f, +, true); Items.Add (Makeitem (items.size () + 1, "Sea View Room 3 Room 2 Hall for Rent", "Sea view garden rental, unbeatable sea view, can see London", 4, 3, 8500f,, false)); Items.Add (Makeitem (items.size () + 1, "Tian-Lan Garden 1-Room 1-Hall", "Tian-yuan garden, male and female limited, stay free hydropower January", 2, 4, 1500f,, true)); Items.Add (Makeitem (items.size () + 1, "God-like beautiful, Jade Villa 3 Room 2 Hall", "heartbeat than action, twist bag can stay, come on!" ", 1, 3, 9500f, 8, false)); Items.Add (Makeitem (items.size () + 1, "2 bedroom 1 Hall," The Lovers Love "," otaku curtilage women come soon as long as 2500, passed by, do not miss ", 1, 2, 2500f, 5, false)); Items.Add (Makeitem (items.size () + 1, "Tian-Lan Garden 3 Room 2 Hall", "Tian-yuan garden rental, all come to see, all to aim, 3 room rental as long as 7500.", 4, 3, 7500f, 6, true); Items.Add (Makeitem (items.size () + 1, "Deep garden for rent 3 rooms 2 Halls", "Find love clean native, new decoration", 4, 3, 5200f,, false)); Items.Add (Makeitem (items.size () + 1, "This is Mobile test", "haha Hello world!", 4, 3, 1200f, +, false)); Core.addbeans (items); Commit core.commit (); ------------------------------------------------------//Set search text ------------------------------------------------------String SearchText = Analysissearchtext (core, "rental garden"); subject:* Rental * && price:[1000 to 8000] System.out.println ("Search Text:" + searchtext); ------------------------------------------------------//Set Query text//----------------------------- -------------------------String QueryText = SearchText + "&& price:[1000 to 8000]"; System.out.println ("Query Text:" + querytext); ------------------------------------------------------//Search//------------------------------------- -----------------solrquery query = new Solrquery (); Query.setquery (QueryText); Query.setstart (0); Number of start lines of query (paging use) query.setrows (100); The number of rows returned by query (paged use) Query.setfacet (true); Set using facet query.setfacetmincount (0); Set the minimum number of facet statistics query.setfacetlimit (10); The number of rows returned by the facet result Query.addfacetfield ("CategoryId", "RegionID"); FACET field Query.setfacetsort (Facetparams.facet_sort_count); Query.addsort (New Sortclause ("id", ORDER.ASC)); Sort Query.setrequesthandler ("/browse"); Queryresponse response = core.query (query); list<item> Items_rep = Response.getbeans (Item.class); list<facetfield> facetfields = Response.getfacetfields (); Since start and rows above are set to 0, there is no query result output System.out.println ("--------------------"); System.out.println ("Search result:"); for (Item item:items_rep) {System.out.println ("id=" + item.getid () + "\tsubject=" + item.getsubject () + "\tregion=" + mapregion.get (Item.getregionid ()) + "\tcategory=" + mapcategory.get (ITEM.G Etcategoryid ()) + "\tprice=" + Item.getprice ()); }//Print all facets for (Facetfield ff:facetfields) {System.out.println ("--------------------"); System.oUt.println ("name=" + ff.getname () + "\tcount=" + Ff.getvaluecount ()); System.out.println ("--------------------"); Switch (Ff.getname ()) {case "RegionID": PrintOut (MapRegion, Ff.getvalues ()); Break Case "CategoryId": PrintOut (Mapcategory, Ff.getvalues ()); Break }}} @SuppressWarnings ({"Rawtypes"}) private static void PrintOut (HashMap map, List<count> Co unts) {for (Count count:counts) {System.out.println ("name=" + map.get (Integer.parseint (count.getname ())) + "\tcount=" + Count.getcount ()); } System.out.println ("--------------------"); } private static Item Makeitem (long ID, string subject, string content, int regionid, int categoryId, float price, Long Point, Boolean vip) {Calendar cale = calendar.getinstance (); Cale.settime (New Date ()); Cale.add (calendar.date, (int) ID); Item item = new Item (); Item.setid (ID); Item.setsubject (subject); Item.setcontent (content); Item.setregionid (RegionID); Item.setcategoryid (CATEGORYID); Item.setprice (price); Item.setcreatetime (Cale.gettime ()); Item.setpoint (point); ITEM.SETVIP (VIP); return item; } @SuppressWarnings ("Unchecked")/** * re-parses the text content that needs to be queried * @param core * @param searchtext * @re Turn * @throws solrserverexception */private static string Analysissearchtext (Httpsolrserver core, String sear Chtext) throws Solrserverexception {StringBuilder strsearchtext = new StringBuilder (); Final String str_field_type = "TEXT_CN"; Solrquery queryanalysis = new Solrquery (); Queryanalysis.add (commonparams.qt, "/analysis/field"); Query type Queryanalysis.add (Analysisparams.field_value, SearchText); Queryanalysis.add (Analysisparams.field_type, Str_field_type);Queryresponse responseanalysis = Core.query (queryanalysis); Parses the response namedlist<object> analysis = (namedlist<object>) responseanalysis.getresponse (). Get ("Analyze ");//Analysis node namedlist<object> field_types = (namedlist<object>) analysis.get (" Field_types ");// Field_types node namedlist<object> FieldType = (namedlist<object>) field_types.get (STR_FIELD_TYPE);//T EXT_CN node Namedlist<object> index = (namedlist<object>) fieldtype.get ("index");//Index node L ist<simpleorderedmap<string>> list = (arraylist<simpleorderedmap<string>>) index.get (" Org.wltea.analyzer.lucene.IKTokenizer ");//Tokenizer node//Add a space in the middle of each entry to perform or operate for each entry for (Iterator<simpleor Deredmap<string>> iter = List.iterator (); Iter.hasnext ();) {Strsearchtext.append (Iter.next (). Get ("text") + ""); } return strsearchtext.tostring (); }}
Description
A) analysissearchtext (...) Method: This method will use the word segmentation analysis, such as the above example "Rent the Garden", call Analysissearchtext (...) to query the statement. , you will get a "rental garden", which will split two words into a space-delimited string. Otherwise, SOLR will be in the "rental garden" as a whole as a word for the query and can not get results.
b) Using a custom handler, you need to include this sentence in your code:
Query.setrequesthandler ("/browse");
corresponding to the Solrconfig.xml in the RequestHandler:/browse
5. Operation Result:
Or, use SOLR query queries to view the results:
SOLR features three: Deftype (query weight sorting)