Cannot click two digit number while Automating Google Calculator using Selenium - selenium

I need to write a code where
a) Go to www.google.com and search for 'calculator'. In the results you will see a calculator coming in the browser itself.
b) Read the Num1 from xls using java code
c) Click the Num1 in calculator of google
Excel File is simple and looks like this.
Num1
7
95
I hope you people understood.
First row Num1
Second row 2
Third row is 95
Using #Test I have written a code
The problem is, I can click Num1 7 but not 95.
Moreover if my num1 is 2 also, it throws me error. Please help.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class Exercise3 {
String part1 = "//*[#id='cwbt";
String part2 = "']/div/span";
#Test(dataProvider="getData")
public void calculator(String num1, String num2, String operation, String expectedResult){
WebDriver d = new FirefoxDriver();
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
d.get("https://www.google.co.in/?gfe_rd=cr&ei=2ArXVu7RGafG8AfjsKPgDQ&gws_rd=ssl#q=calculator");
//calculator box
//*[#id='cwbt13']/div/span
//*[#id='cwbt23']/div/span
//*[#id='cwbt33']/div/span
//*[#id='cwbt43']/div/span
WebElement box = d.findElement(By.xpath("//*[#id='cwmcwd']"));
for(int i=13;i<=46;i++){
String num = d.findElement(By.xpath("//*[#id='cwbt"+i+"']/div/span")).getText();
if(num.equals(num1)){
d.findElement(By.xpath("//*[#id='cwbt"+i+"']/div/span")).click();
break;
}
}
}
#DataProvider
public Object[][] getData(){
Xls_Reader xls = new Xls_Reader("E:\\Pessoal\\QTPSelenium\\Excel\\Calculator.xlsx");
int rows = xls.getRowCount("Addition");
int cols = xls.getColumnCount("Addition");
Object data[][] = new Object[rows-1][cols-2];
for(int rNum=2;rNum<=rows;rNum++){
for(int cNum=0;cNum<cols-2;cNum++){
System.out.println(xls.getCellData("Addition", cNum, rNum));
data[rNum-2][cNum] = xls.getCellData("Addition", cNum, rNum);
}
}
return data;
}
}

try following code/ I have updated according to Java Lang
FirefoxDriver driver;
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.get("https://www.google.co.in/?gfe_rd=cr&ei=2ArXVu7RGafG8AfjsKPgDQ&gws_rd=ssl#q=calculator");
String strJavaScript = "document.getElementById('cwos').textContent= " + num1.trim() + " " + operation.trim() + " " + num2.trim() ;
Object obj;
//org.openqa.selenium.JavascriptExecutor.class.
obj = driver.executeScript(strJavaScript, (Object) null);
driver.findElement(By.xpath(".//*[#id='cwbt45']/div/span")).click();
String answer = driver.findElement(By.id("cwos")).getText();
if (expectedAnswer == null ? answer == null : expectedAnswer.equals(answer)) {
System.out.println("Expected answer and given answer are same.");
}
else
System.out.println("Expected answer and given answer are not same.");
System.out.print(answer);
if any issue then let me know.

Related

Selenium - Unable to pick particular rows from TestData excel file

I am trying to build the TestDataReader.java file. My code should pick only the rows which are tagged by the particular testcaseid (For eg: for Test Case 1, it should pick only rows with TC_001, for Test Case 2 it should pick only rows with TC_002) and return the data to the Dataprovider method. With the below attached code, When i pass Test Case ID as TC_002, it is putting null in the testData[rowNum][0] column for rows with TC_001.
My expectation is that i should get rows only for TC_002. it should not process for TC_001.
Please suggest what is incorrect in this code.
Below is my TestDatareader class:
package com.automation.website.kaspick.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestDataReader {
XSSFWorkbook xlWorkbook = null;
XSSFSheet sheet = null;
XSSFRow row = null;
XSSFCell cell = null;
String currentDir = Paths.get("").toAbsolutePath().toString();
String testDataFileName = "\\TestData\\TestData.xlsx";
String sheetName = null;
String xlFilePath = currentDir + testDataFileName;
public Object[][] readTestData(String sheetName, String testCaseID) throws IOException {
String rowHeader = null;
String columnValue = null;
FileInputStream fileInputStream = new FileInputStream(xlFilePath);
xlWorkbook = new XSSFWorkbook(fileInputStream);
sheet = xlWorkbook.getSheet(sheetName);
int rowCount = sheet.getLastRowNum();
Object[][] testData = new Object[rowCount][1]; // This object is created to store the MapData as an object for
// DataProvider
if (sheet.getSheetName().equalsIgnoreCase(sheetName)) {
for (int rowNum = 0; rowNum < rowCount; rowNum++) {
HashMap<Object, Object> testDataInEachRow = new HashMap<Object, Object>();
row = sheet.getRow(rowNum + 1); // Since the first row will be header, parse from the second row
int columnCount = row.getLastCellNum();
for (int colNum = 0; colNum < columnCount; colNum++) {
rowHeader = sheet.getRow(0).getCell(colNum).toString();
if(colNum==0 && !row.getCell(colNum).toString().equalsIgnoreCase(testCaseID)) {
break;
}
if (row.getCell(colNum) != null) {
columnValue = row.getCell(colNum).toString();
} else {
columnValue = "";
}
testDataInEachRow.put(rowHeader, columnValue);
}
}
testData[rowNum][0] = testDataInEachRow;
}
return testData;
}
}
Below is my Test Data. I have masked the data
[TestData.xlsx][1]
[1]: https://i.stack.imgur.com/h6cMf.png

how to get text from span in the below code

I want to get text from all the check boxes given in a drop down box in order to compare those values with db. Please help me. I am able to count the size by options.size(), but unable to get the text/strings to compare with each string in db.
//Click on Select Box
Thread.sleep(500);
driver.findElement(By.xpath(".//*[#id='DivZone']/div/button")).click();
Thread.sleep(500);
List<WebElement> options =
driver.findElements(By.xpath("//input[contains(#name,
'multiselect_ddlZone')]"));
//List<WebElement> options = driver.findElements(By.cssSelector(".ui-
corner-all.ui-state-hover>span"));
List<String> all_elements_text=new ArrayList<>();
if(region!=null)
{
for(int i=1; i<options.size(); i++)
{
all_elements_text.add(options.get(i).getText());
System.out.println(options.get(i).getText());
boolean isThere = false;
for (int j = 0; j < region.size(); j++)
{
if
(options.get(i).getText().equalsIgnoreCase(region.get(j))) {
// Code to display warning
isThere = true;
}
}
if(isThere)
System.out.println(options.get(i).getText()+" is matched
with Database data");
else
System.out.println(options.get(i).getText()+" is not matched
with Database data");
}
}
If unfortunately getText() doesn't work, you should try using getAttribute("textContent"‌​) as below :-
System.out.println(options.get(i).getAttribute("textContent"‌));
Or try using getAttribute("innerHTML"‌) as below :-
System.out.println(options.get(i).getAttribute("innerHTML"‌));
Right now, each "option" is an "input" WebElement, which will not have any text.
You may want to try searching for the list items, then pulling out the span content:
List<WebElement> options = driver.findElements(By.cssSelector("ul.ui-multiselect-checkboxes li label[for*='ddlZone'] span"));
Gave it a try on "www.tripadvisor.in", and able to make it (Used 'break' statement just to limit the loop in the example). Below is the code I tried on
public class SelectList {
WebDriver driver;
By currencyDrop = By.xpath(".//*[#id='CURRENCYPOP']/span");
By currency = By.xpath(".//*[#id='GLOBAL_CURRENCY_PICKER']/ul/li");
#Test
public void f() throws InterruptedException {
driver = new FirefoxDriver();
driver.get("https://www.tripadvisor.in/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(currencyDrop).click();
//Below is the list of options present in dropdown(per DB)
String[] expList = {"INR ₹ Indian Rupees",
"USD US$ U.S. Dollars",
"EUR € Euros"};
List <WebElement>countryList = driver.findElements(currency);
int i =0;
for(WebElement curr:countryList){
if (i>2){
break;
}
if (curr.getText().equals(expList[i])){
System.out.println("ActCurrency" + curr.getText());
System.out.println("ExpCurrency" + expList[i]);
i++;
}
}
}
}

Run Multiple test cases with multiple test data sheet

I need help in selenium. I am trying to run multiple test cases with multiple test data sheets with TestNG and Data Provider concept. But I am having issue in running the test data. If I return array in Test, after getting the test data from sheet then starting from the one row of test cases again so it always run 1st row of the Data driven function.
If I return at the end of the DataDriven then last row will print the value in Test rest would get overnight.
Please let me know what I have to do to run the my test cases. I am attaching the code and Test cases and Test data sheet.
Test Cases & test data sheet
package testCases;
import java.util.Properties;
import operation.ReadObject;
import operation.UIOperation;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Iterator;
import java.lang.reflect.Method;
import excelExportAndFileIO.ReadExcelFile;
public class Test1 {
private static final Boolean True = null;
//WebDriver webdriver = null;
public static WebDriver driver;
private Cell Cell;
private Cell TCCellValue;
/* #BeforeSuite
public static void firefoxSetUp() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
}
#AfterSuite
public static void closeFirefox(){
driver.quit();
}*/
#Test(dataProvider = "hybridData")
public void Permittee_Registration(String Status, String TC, String Module1, String Module2 ) { //String Status, String TCName, String TCDesc) throws Exception {
System.out.println("Status:"+Status +" ; TC:"+TC + " ; Module1:"+Module1 + " ; Module2:"+Module2);
}
// Call the test data sheet ----- PR = Permittee Registration
#Test(dataProvider = "hybridData")
public void PR_Applicant_Information(String TestCase, String URL, String objPermittee, String objPR, String PR_TITLE, String objLegal_Entity_Type, String Permittee_Legal_Name, String EIN ) {
System.out.println("PR_Applicant_Information Test");
if (TestCase!=null){
System.out.println("");
System.out.println("TestCase:"+TestCase + " ; PR_Applicant_Information URL:"+URL + " ; objPermittee: "+objPermittee + " ; objPR: " +objPR + " ; PR_TITLE: " +PR_TITLE + " ; objLegal_Entity_Type: " +objLegal_Entity_Type + " ; Permittee_Legal_Name: " + " ; EIN: " +EIN + "; dd: dd") ;
}
}
#Test(dataProvider = "hybridData")
public void PR_Choose_Qualification(String TC, String URL){
if (TC!=null){
System.out.println("");
System.out.println("PR_Choose_Qualification TC:"+TC + " ; URL: "+ URL);
}
}
#DataProvider(name = "hybridData")
public Iterator[] loginData(Method method) {
//System.out.println("Hybrid");
String TCName="";
Object[][] result = null;
Object[][] testData = new String[10][10];
Object[][] arrayObject = getExcelData(("user.dir") + "\\TestCaseSheet.xlsx", "TestCases_Modules",TCName);
//K=Row and L=Column
for (int k=0; k < arrayObject.length; k++){
int colCount=arrayObject[k].length;
//System.out.println("Column=arrayObject[k].length:"+arrayObject[k].length);
if ("YES".equals(arrayObject[k][0])){
//System.out.println("arrayObject[k][L]:"+arrayObject[k][L]+" ; K="+k+" ; L="+L);
//System.out.println("arrayObject[k][0]----:"+arrayObject[k][0] +" ; K = "+k );
for (int L=0; L< colCount ; L++){
//"Permittee_Registration"
//System.out.println("Permittee_Registration"+arrayObject[k][2]);
if ((arrayObject[k][L] !=null) && ((String)arrayObject[k][L]).indexOf(",") > 0) {
String[] pr = ((String)arrayObject[k][L] ).split(",");
//System.out.println("pr:"+pr.length + " ; PRValue:"+pr[0]);
for (int prN=0; prN < pr.length; prN++ ){
//System.out.println("for (int prN=0; prN < pr.length; prN++ )");
//pr=Applicant_Information
TCName=(String) arrayObject[k][1]; //fetching the Test Case Name
//System.out.println("TCName:"+TCName + " ; equals(pr[prN]) = "+equals(pr[prN]) + " ; pr.length="+pr.length + " ; pr[prN]="+ pr[prN]);
if ("Applicant_Information".equals(pr[prN])){
System.out.println("if (Applicant_Information.equals(pr[prN]))"+pr[prN] + " ; pr.length="+pr.length );
if (method.getName().equals("PR_Applicant_Information")) {
System.out.println("Applicant_Information Moni before calling excel sheet function:"+" ; result.length"+result.length);
//result = getExcelData(("user.dir") + "\\TestCaseSheet.xlsx", "Applicant_Information",TCName);
result = getExcelData(("user.dir") + "\\TestCaseSheet.xlsx", pr[prN] ,TCName);
//AI(result);
//System.out.println("Applicant_Information Moni afte calling excel sheet function:"+" ; result.length"+result.length);
//return result;
};
}
else if ("Choose_Qualification".equals(pr[prN])){
if (method.getName().equals("PR_Choose_Qualification")) {
//System.out.println("Choose_Qualification Moni before calling excel sheet function:"+pr[prN] +" ; result.length"+result.length);
result = getExcelData(("user.dir") + "\\TestCaseSheet.xlsx", "Choose_Qualification",TCName);
System.out.println("Choose_Qualification Moni after calling excel sheet function:"+pr[prN] +" ; result.length"+result.length);
};
}
}
//return result;
}
}
}
}
return result;
}
public void AI(Object result){
System.out.println("resultAI:"+result);
}
/**
* #param File
* Name
* #param Sheet
* Name
* #return
*/
public String[][] getExcelData(String fileName, String sheetName, String TCName) {
//public List<String> getExcelData(String fileName, String sheetName, String TCName) {
String[][] arrayExcelData = null;
int a=0;
int b=0;
try {
ReadExcelFile file = new ReadExcelFile();
// UIOperation operation = new UIOperation(driver);
// Read keyword sheet
Sheet testCaseSheet = file.readExcel(System.getProperty("user.dir") + "\\", "TestCaseSheet.xlsx", sheetName);
// Find number of rows in excel file
int rowCount = testCaseSheet.getLastRowNum() - testCaseSheet.getFirstRowNum();
int coulmnCount = testCaseSheet.getRow(0).getLastCellNum();
int firstCoulmnCount = testCaseSheet.getRow(0).getFirstCellNum();
arrayExcelData=new String[rowCount+1][coulmnCount];
//System.out.println("rowCount:"+rowCount);
//System.out.println("coulmnCount:"+coulmnCount);
//Looping the row
for (int i = testCaseSheet.getFirstRowNum(); i < (testCaseSheet.getLastRowNum()+1) ; i++) {
// Loop over all the rows
//Row row=testCaseSheet.getRow(i + 1);
int j;
if ("" != (TCName)){
//Object TCCellValues = null;
}
for (j = firstCoulmnCount; j < coulmnCount ; j++) {
Cell = testCaseSheet.getRow(i).getCell(j);
//System.out.println("TCName in recurring function :"+TCName);
//System.out.println("Cell:"+Cell);
//if TCName is equal to particular row then pick only that cell data.
TCCellValue = testCaseSheet.getRow(i).getCell(0);
String TCCellValues = TCCellValue.getStringCellValue();
//System.out.println("if ( != (TCCellValue)): " +TCCellValue + " ; TCName=" + TCName + " ; i="+i);
String CellData="";
//System.out.println("Cell inside:"+Cell);
if (Cell!=null){
CellData = Cell.getStringCellValue();
//System.out.println(i+":"+CellData);
}
if (TCName.equals("")||(TCName.equals(TCCellValues))){
arrayExcelData[i][j]=CellData;
//System.out.println("arrayExcelData[i][j]=CellData;"+CellData + " ; i="+i +" ; j="+j + " ; TCName="+TCName + " ; a="+a +" ; b="+b );
}
}
}
} catch (Exception e) {
System.out.println("Error " + e);
}
//System.out.println("Stop_arrayExcelData:");
return arrayExcelData;
//return new List<String>{{arrayExcelData}};
}
}

get count for rolling date value Using Apache Pig

How can we achieve using Apache Pig :
File :
A 2014/10/01
A 2014/09/01
A 2014/08/01
A 2014/02/01
Result should A count 3, since i want to count the number of records using rolling window of 30 days between records group by A.
Please find the solution, i hope you can do further enhancement if it required. Try to execute with your input and let me know how it works.
input.txt
A 2014/12/01
A 2014/11/01
A 2014/10/01
A 2014/07/01
A 2014/05/01
A 2014/04/01
B 2014/09/01
B 2014/07/01
B 2014/06/01
B 2014/02/01
C 2014/09/01
C 2014/07/01
C 2014/05/01
Expected output
A 5
B 2
C 0
PigScript:
REGISTER rollingCount.jar;
A = LOAD 'input.txt' Using PigStorage(' ') AS (f1:chararray,f2:chararray);
B = GROUP A BY f1;
C = FOREACH B GENERATE mypackage.ROLLINGCOUNT(BagToString($1)) AS rollingCnt;
DUMP C;
OutPut from the Script:
(A,5)
(B,2)
(C,0)
Java Code:
1. Compile the below java code and create jar file name rollingCount.jar
2. I just wrote the code temporarily, you can optimize if required.
ROLLINGCOUNT.java
package mypackage;
import java.io.*;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import java.util.*;
public class ROLLINGCOUNT extends EvalFunc<Integer> {
public Integer exec(Tuple input) throws IOException {
//Get the input String from request
String inputString = (String)input.get(0);
Date[] arrayOfDates = getArrayOfDate(inputString);
long diffDays[] = getDaysBetweenList(arrayOfDates);
int rollingCount = getRollingCount(diffDays);
return rollingCount;
}
//Function to convert strings to array of dates
static protected Date[] getArrayOfDate(String inputString)
{
//Get the 1st column, this will be the Id
String ID = inputString.split("_")[0];
//Replace all the Ids with Null, bcoz its a duplicate columns
String modifiedString = inputString.replace(ID+"_","");
//Split the string into multiple columns using '_' as delimiter
String list[] = modifiedString.split("_");
//Convert the string to list of array dates
Date[] dateList = new Date[list.length];
int index=0;
for (String dateString: list)
{
try
{
//Convert the date string to date object in the give format
SimpleDateFormat dFormat = new SimpleDateFormat("yyyy/MM/dd");
dateList[index++] = dFormat.parse(dateString);
}
catch(Exception e)
{
// error handling goes here
}
}
return dateList;
}
//Function to get difference between two dates
static protected long[] getDaysBetweenList(Date[] arrayOfDate)
{
long diffDays[] = new long[arrayOfDate.length-1];
int cnt=0;
for (int index=0; index<arrayOfDate.length-1;index++)
{
long diff = Math.abs(arrayOfDate[index+1].getTime() - arrayOfDate[index].getTime());
long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
diffDays[cnt++] = days;
}
return diffDays;
}
//Function to get the total rolling count
static protected int getRollingCount(long diffDays[])
{
int result =0;
for(int index=0;index<diffDays.length;index++)
{
int cnt =0;
//hardcoded the values of 30 and 31 days, may need to handle Feb month 28 or 29 days
while((index<diffDays.length)&&((diffDays[index]==30)||(diffDays[index]==31)))
{
cnt++;
index++;
}
if(cnt>0)
{
result = result + cnt+1;
}
}
return result;
}
}

Lucene custom scoring for numeric fields

I would like to have, in addition to standard term search with tf-idf similarity over text content field, scoring based on "similarity" of numeric fields. This similarity will be depending on distance between the value in query and in document (e.g. gaussian with m= [user input], s= 0.5)
I.e. let's say documents represent people, and person document have two fields:
description (full text)
age (numeric).
I want to find documents like
description:(x y z) age:30
but age to be not the filter, but rather part of score (for person of age 30 multiplier will be 1.0, for 25-year-old person 0.8 etc.)
Can this be achieved in a sensible manner?
EDIT: Finally I found out this can be done by wrapping ValueSourceQuery and TermQuery with CustomScoreQuery. See my solution below.
EDIT 2: With fast-changing versions of Lucene, I just want to add that it was tested on Lucene 3.0 (Java).
Okay, so here's (a bit verbose) proof-of-concept as a full JUnit test. Haven't tested its efficiency yet for large index, but from what I've read probably after a warm-up it should perform well, providing there's enough RAM available to cache numeric fields.
package tests;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.function.CustomScoreQuery;
import org.apache.lucene.search.function.IntFieldSource;
import org.apache.lucene.search.function.ValueSourceQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import junit.framework.TestCase;
public class AgeAndContentScoreQueryTest extends TestCase
{
public class AgeAndContentScoreQuery extends CustomScoreQuery
{
protected float peakX;
protected float sigma;
public AgeAndContentScoreQuery(Query subQuery, ValueSourceQuery valSrcQuery, float peakX, float sigma) {
super(subQuery, valSrcQuery);
this.setStrict(true); // do not normalize score values from ValueSourceQuery!
this.peakX = peakX; // age for which the age-relevance is best
this.sigma = sigma;
}
#Override
public float customScore(int doc, float subQueryScore, float valSrcScore){
// subQueryScore is td-idf score from content query
float contentScore = subQueryScore;
// valSrcScore is a value of date-of-birth field, represented as a float
// let's convert age value to gaussian-like age relevance score
float x = (2011 - valSrcScore); // age
float ageScore = (float) Math.exp(-Math.pow(x - peakX, 2) / 2*sigma*sigma);
float finalScore = ageScore * contentScore;
System.out.println("#contentScore: " + contentScore);
System.out.println("#ageValue: " + (int)valSrcScore);
System.out.println("#ageScore: " + ageScore);
System.out.println("#finalScore: " + finalScore);
System.out.println("+++++++++++++++++");
return finalScore;
}
}
protected Directory directory;
protected Analyzer analyzer = new WhitespaceAnalyzer();
protected String fieldNameContent = "content";
protected String fieldNameDOB = "dob";
protected void setUp() throws Exception
{
directory = new RAMDirectory();
analyzer = new WhitespaceAnalyzer();
// indexed documents
String[] contents = {"foo baz1", "foo baz2 baz3", "baz4"};
int[] dobs = {1991, 1981, 1987}; // date of birth
IndexWriter writer = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED);
for (int i = 0; i < contents.length; i++)
{
Document doc = new Document();
doc.add(new Field(fieldNameContent, contents[i], Field.Store.YES, Field.Index.ANALYZED)); // store & index
doc.add(new NumericField(fieldNameDOB, Field.Store.YES, true).setIntValue(dobs[i])); // store & index
writer.addDocument(doc);
}
writer.close();
}
public void testSearch() throws Exception
{
String inputTextQuery = "foo bar";
float peak = 27.0f;
float sigma = 0.1f;
QueryParser parser = new QueryParser(Version.LUCENE_30, fieldNameContent, analyzer);
Query contentQuery = parser.parse(inputTextQuery);
ValueSourceQuery dobQuery = new ValueSourceQuery( new IntFieldSource(fieldNameDOB) );
// or: FieldScoreQuery dobQuery = new FieldScoreQuery(fieldNameDOB,Type.INT);
CustomScoreQuery finalQuery = new AgeAndContentScoreQuery(contentQuery, dobQuery, peak, sigma);
IndexSearcher searcher = new IndexSearcher(directory);
TopDocs docs = searcher.search(finalQuery, 10);
System.out.println("\nDocuments found:\n");
for(ScoreDoc match : docs.scoreDocs)
{
Document d = searcher.doc(match.doc);
System.out.println("CONTENT: " + d.get(fieldNameContent) );
System.out.println("D.O.B.: " + d.get(fieldNameDOB) );
System.out.println("SCORE: " + match.score );
System.out.println("-----------------");
}
}
}
This can be achieved using Solr's FunctionQuery